Game Development Reference
In-Depth Information
}
Optionals are useful when there is a possibility that a variable will not contain a value.
One way this can happen is when you are searching for something in a collection and the
value is not found—an address in this instance. Note the exclamation mark ( ! ) after the
variable in println() . You use this operator to unwrap the optional. If you do not un-
wrap the optional, the compiler will not recognize the type of your variable.
There is another way to unwrap an optional. Take the previous address instance. You can
use an if or case statement to store an optional's unwrapped value in a constant.
if let address = optionalAddress {
println("The number is \(address.number())")
}
Using the if like this automatically unwraps the optional and stores it in the constant
address .
for Loops
Swift provides two different implementations of the for loop: for-conditional-
increment looping and for-in looping.
for-conditional-increment
The for-conditional-increment implementation of the for loop is the imple-
mentation you have probably used for years. This version of the for loop is the tradition-
al C-style loop that uses an initializer, a condition, and an incrementer separated by semi-
colons. Take a look at this loop:
var colors = ["red", "blue", "green", "black", "blue",
"orange"]
for var index = 0; index < colors.count; index++ {
println("The color is : \(colors[index])")
}
In this example, you create an array of strings representing different colors. You then use
an Int value named index to iterate over the array and print its values. We have all seen
this type of loop a million times.
Search WWH ::




Custom Search