Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

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.