Changes

Swift Data Types, Constants and Variables

955 bytes added, 21:22, 13 April 2015
The Swift Optional Type
In this case the value assigned to the index variable is unwrapped and assigned to a temporary constant named myvalue which is then used as the index reference into the array. Note that the myvalue constant is described as temporary since it is only available within the scope of the if statement. Once the if statement completes execution, the constant will no longer exist.
 
Optional binding may also be used to unwrap multiple optionals and include a Boolean test condition, the syntax for which is as follows:
 
<pre>
if let constname1 = optName1, constname2 = optName2, optName3 = … where <boolean statement> {
 
}
</pre>
 
The following code, for example, uses optional binding to unwrap two optionals within a single statement:
 
<pre>
var pet1: String?
var pet2: String?
 
pet1 = "cat"
pet2 = "dog"
 
if let firstPet = pet1, secondPet = pet2 {
println(firstPet)
println(secondPet)
} else {
println("insufficient pets")
}
</pre>
 
The code fragment below, on the other hand, also makes use of the where clause to test a Boolean condition:
 
<pre>
if let firstPet = pet1, secondPet = pet2 where petCount > 1 {
println(firstPet)
println(secondPet)
} else {
println("no pets")
}
</pre>
 
In the above example, the optional binding will not be attempted unless the value assigned to petCount is greater than 1.
It is also possible to declare an optional as being implicitly unwrapped. When an optional is declared in this way, the underlying value can be accessed without having to perform forced unwrapping or optional binding. An optional is declared as being implicitly unwrapped by replacing the question mark (?) with an exclamation mark (!) in the declaration. For example: