Inconsistent error with array of Range<String.Index> Items

Seeing different behaviour when similar code is presented in a Mac app and either a Mac Playground or command line app.

The objective is create an array of range references into a string.

Code Block
/* Define a string */
let source = "Hello"
/* Define an array that is a collection of ranges within the string. In this case use the whole range. */
let array = [source.startIndex..<source.endIndex, source.startIndex..<source.endIndex]
/* Iterate */
for r in array
{
...
}


This works in the Playground and Command Line versions but in a Mac app, the same code produces:

For-in loop requires 'Range<String.Index>?' to conform to 'Sequence'; did you mean to unwrap optional?

The Range<String.Index> items in the array are themselves not Sequences.

Unclear why essentially the same code loop is producing an error message when used in the Mac app but no error for the Playground or command line. Nothing defined is an optional.

Experimented with 12.1 and 12.2 - same results so far.

Has anybody seen anything similar?
Writing a wrapper class around the range seems to be one work around.

However, there is a bizarre issue where the code compiles and runs in the app, but unit testing reports the same error.

Clean and option Clean tried, with no success.
I’m not seeing the same results as you. Here’s what I did:
  1. In Xcode 12.2, I created a new command-line tool project (macOS > Command Line Tool).

  2. I then replaced main.swift with your code, applying a single tweak to get it to compile (I replaced line 12 with print(r)).

  3. I did a Product > Build and saw no errors.

  4. I created a new Mac app project (macOS > App), selecting the Storyboard interface.

  5. I added the code from step 2 to the end of the applicationDidFinishLaunching(_:) method in AppDelegate.swift.

  6. I did a Product > Build and it built just fine.

Clearly I’m missing some subtlety but I’m not sure what that it is. Can you repeat the steps above and let me know what you get?

Share and Enjoy

Quinn “The Eskimo!” @ Developer Technical Support @ Apple
let myEmail = "eskimo" + "1" + "@apple.com"
Inconsistent error with array of Range&lt;String.Index&gt; Items
 
 
Q