- General Changes
- Loops
- Conditionals
- To Integers and Beyond!
- Wrapping Up
Conditionals
Conditionals in Swift also come in the same two types as Objective-C: the largely unchanged if statement and the radically overhauled switch statement.
if
Like while loops, the if conditional statement in Swift has mainly the same behaviors as its counterpart in Objective-C. As with the other control statements, it is subject to the changes in parentheses and braces, and again requires the conditional expression to conform to the BooleanType. Also like the while statement, if can be used with optional binding to guard against optional variables whose current value is nil.
switch
Of all the flow control statements, the humble switch has probably changed the most. In Objective-C, describing switch as an alternative way of writing a series of if statements would be fair. For example, consider this sequence of if statements:
The alternative in terms of the switch statement is:
Two major changes to the way switch works in Swift have greatly enhanced its powers: an ability to switch on more than just integer values, and the ability to employ pattern-matching techniques. Swift also brings a number of smaller changes that make switch statements a little less error-prone than before.