Reputation: 103
Excerpt from The Swift Programming Language (Swift 4.2) documentation by Apple.
let greeting = "Hello, world!"
let index = greeting.firstIndex(of: ",") ?? greeting.endIndex
let beginning = greeting[..<index]
The above example works totally fine except after I exclude the Nil-coalescing part of the code.
let beginning = greeting[..<greeting.firstIndex(of: ",")]
By leaving out the ?? greeting.endIndex
, Xcode returns an error.
The question is why is it necessary?
Why can't we just use firstIndex()
directly to access the substring.
Upvotes: 1
Views: 783
Reputation: 11242
Consider this example.
let greeting = "Hey There!"
let index = greeting.firstIndex(of: ",")
index
is of type Index?
, so it can be nil. Since the string has no ',', the value of index is nil.
So this code becomes illegal. Since index cannot be an optional value.
let beginning = greeting[..<index]
You can alternatively unwrap it and get the index if it is valid index like this.
guard let indexFound = index else {
print("Character not) found in string"
return
}
let beginning = greeting[..<indexFound]
print("The first occurance of the character is at \(beginning).")
Real world example: (I know it's not good, but it should be enough :x)
Remember the bot captcha's that pop up in websites? The ones that ask you to identify the number of cars, street signs etc. So there you click on the boxes which show the requirement. and click 'submit'. But if there aren't any, you click 'Skip'. So drawing parallels. If you have a valid index, it returns the valid index, otherwise it return
nil
which is not an validIndex
, but it is a valid answer to the question asked. (Is there a ',' inside the string?) The problem here is, the next part. Slicing an array requires you to have a validIndex
, so yourindex
currently is an optional which you can change to a valid index by safely unwrapping like my example or having a nil-coalescing check at the time of getting the index.
You should look up optionals in Swift to get a better understanding.
Upvotes: 2
Reputation: 100533
As it may be no index for the supplied character , so following your way the app will crash
func firstIndex(of element: Character) -> String.Index?
The optional return String.Index?
solves it , and that's why you need ??
if you don't supply ??
Then you have to force unwrap let beginning = greeting[..<index]
here index should be index!
which will cause a crash if it's nil
Upvotes: 3