Game Development Reference
In-Depth Information
The Swift switch statement is powerful. Unlike with Objective-C, you can test any type
of value in a switch statement. The Swift switch statement has another difference
from the Objective-C switch statement. It does not require break statements. The case
ends at the next case or default statement. Take a look at this Swift switch statement:
var food = "broccoli"
switch food {
case "cheeseburger":
println("YUM")
case "broccoli":
println("YUCK")
default:
println("UKNOWN FOOD")
}
In this switch you are testing String values. Notice there are no breaks. Go ahead and
copy this snippet into your main.swift file and run the code. You will get exactly what
you would expect—“YUCK.”
Try one more thing. Go back to this code in Xcode and remove the default section of the
switch . You will see the following error:
Switch must be exhaustive, consider adding a dafault clause
Every switch statement must be exhaustive, which means that every possibility of the
type being tested must have a matching case. In this case of a String , this is impossible,
which is why you need the default clause at the end of the switch .
There is one last thing I need to discuss: optionals. Optionals are Swift variables that can
have a value or have no value and are set to nil . The syntax of an optional is the same as
a normal variable declaration, except you add a question mark ( ? ) after the type of the
variable.
var optionalAddress : String?
This variable optionalAddress can either have an Address value or have no value.
You can use an if to see whether the variable has a value.
if optionalAddress {
println("The number is \(optionalAddress!.number())")
Search WWH ::




Custom Search