Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

iOS

Gene Bogdanovich
Gene Bogdanovich
14,618 Points

CountableRange Question

Consider this code:

let greeting = "hello world"
if let firstSpace = greeting.index(of: " ") {
    let secondWordIndex = greeting.index(firstSpace, offsetBy: 1)
    let secondWord = greeting[secondWordIndex..<greeting.endIndex] // "world"
}

Why do we use half-open range operator (..<) instead of closed range operator (…) to get the second word?

1 Answer

Addison Francisco
Addison Francisco
9,561 Points

Hey Gene,

A half-open range operator is required in this example because you are subscripting with String.endIndex which returns the index after the last character in the collection. For your example, you want the index right before that. Using a half-open range operator achieves just that. Alternatively, you could use index(before:) with a closed range operator to achieve the same result

let secondWord = greeting[secondWordIndex...greeting.index(before: greeting.endIndex)]
Gene Bogdanovich
Gene Bogdanovich
14,618 Points

Thank you very much! That surely cleared things up for me.