According to Apple's Swift guide, when you have the following Array and the following function to search through an Array:
let namesArray = ["John", "Lisa", "Bill", "Jennifer"]
// Note this function is set-up to return an OPTIONAL Int:
func findName (personName:String, arrayToSearchIn:String[]) -> Int? {
for (indexOfName, nameValue) in enumerate(arrayToSearchIn) {
if nameValue == personName {
return indexOfName
}
}
return nil
}
...so you can capture the Optional Int returned by this function - and then check to see if its nil
or not - in the following manner:
let nameIndex: Int? = findName("Lisa", arrayToSearchIn: namesArray)
if nameIndex {
println("found \(namesArray[nameIndex!])")
}
else {
println("NOT found")
}
This is all good - but their next example, in which they streamline the code by collapsing the 2 statements into one - confuses me because they suddenly drop the Optional "?" and "!" from their syntax:
if let nameIndex = findName("Lisa", arrayToSearchIn: namesArray) {
println("found \(namesArray[nameIndex])")
}
And this works perfectly well.
So why is it that in the first example nameIndex
was declared with a "?" - like so:
nameIndex:Int?
and the forced-unwrapping occurs using a "!"
[nameIndex!]
but in the second example neither "?" or "!" one is used in the syntax?
?
is the operator to explicitly declare an optional type.!
is the operator to force-unwrap an optional. The syntax in the example is a special Swift shorthand for checking and unwrapping in one concise line. It says, “assignnameIndex
to the result offindName(...)
, and if it is notnil
, run the following code: ...”