Control Flow For Swift
Swift provides a variety of control flow statements. These include
while
loops to perform a task multiple times; if
, guard
, and switch
statements to execute different branches of code based on certain conditions; and statements such as break
and continue
to transfer the flow of execution to another point in your code.
Swift also provides a
for
-in
loop that makes it easy to iterate over arrays, dictionaries, ranges, strings, and other sequences.
Swift’s
switch
statement is considerably more powerful than its counterpart in many C-like languages. Cases can match many different patterns, including interval matches, tuples, and casts to a specific type. Matched values in a switch
case can be bound to temporary constants or variables for use within the case’s body, and complex matching conditions can be expressed with a where
clause for each case.For-In Loops :
let names = ["Anna", "Alex", "Brian", "Jack"]
for name in names {
print("Hello, \(name)!")
}
for index in 1...5 {
print("\(index) times 5 is \(index * 5)")
}
// 1 times 5 is 5
// 2 times 5 is 10
// 3 times 5 is 15
// 4 times 5 is 20
// 5 times 5 is 25
While Loops :
Swift provides two kinds of
while
loops:1. while
evaluates its condition at the start of each pass through the loop.2. repeat
-while
evaluates its condition at the end of each pass through the loop.while condition {
statements
}
For Example :
var square = 0
var diceRoll = 0
while square < finalSquare {
// roll the dice
diceRoll += 1
if diceRoll == 7 { diceRoll = 1 }
// move by the rolled amount
square += diceRoll
if square < board.count {
// if we're still on the board, move up or down for a snake or a ladder
square += board[square]
}
}
print("Game over!")
Repeat-While :
repeat {
statements
-
} while condition
For example :repeat {
// move up or down for a snake or ladder
square += board[square]
// roll the dice
diceRoll += 1
if diceRoll == 7 { diceRoll = 1 }
// move by the rolled amount
square += diceRoll
} while square < finalSquare
print("Game over!")
Conditional Statements :
If : All know about this one. and its simplest form, the
if
statement has a singleif
condition. It executes a set of statements only if that condition istrue
.
temperatureInFahrenheit = 72
if temperatureInFahrenheit <= 32 {
print("It's very cold. Consider wearing a scarf.")
} else if temperatureInFahrenheit >= 86 {
print("It's really warm. Don't forget to wear sunscreen.")
}
Switch : Aswitch
statement considers a value and compares it against several possible matching patterns. It then executes an appropriate block of code, based on the first pattern that matches successfully. Aswitch
statement provides an alternative to theif
statement for responding to multiple potential states.switch some value to consider {
case value 1:
respond to value 1
case value 2,
-
value 3:
-
respond to value 2 or 3
default:
-
otherwise, do something else
}
For example :
let someCharacter: Character = "z"
switch someCharacter {
case "a":
print("The first letter of the alphabet")
case "z":
print("The last letter of the alphabet")
default:
print("Some other character")
}
// Prints "The last letter of the alphabet"
Theswitch
statement’s first case matches the first letter of the English alphabet,a
, and its second case matches the last letter,z
. Because theswitch
must have a case for every possible character, not just every alphabetic character, thisswitch
statement uses adefault
case to match all characters other thana
andz
. This provision ensures that theswitch
statement is exhaustive.No Implicit Fallthrough :
let anotherCharacter: Character = "a"
switch anotherCharacter {
case "a": // Invalid, the case has an empty body
case "A":
print("The letter A")
default:
print("Not the letter A")
}
// This will report a compile-time error. So on 'case "a" needs some statement or a 'break" key word.
Interval Matching : New features for Switch in side Swift:
Values inswitch
cases can be checked for their inclusion in an interval. This example uses number intervals to provide a natural-language count for numbers of any size:
let approximateCount = 62
let countedThings = "moons orbiting Saturn"
let naturalCount: String
switch approximateCount {
case 0:
naturalCount = "no"
case 1..<5:
naturalCount = "a few"
case 5..<12:
naturalCount = "several"
case 12..<100:
naturalCount = "dozens of"
case 100..<1000:
naturalCount = "hundreds of"
default:
naturalCount = "many"
}
print("There are \(naturalCount) \(countedThings).")
// Prints "There are dozens of moons orbiting Saturn."
Tuples :
You can use tuples to test multiple values in the sameswitch
statement. Each element of the tuple can be tested against a different value or interval of values. Alternatively, use the underscore character (_
), also known as the wildcard pattern, to match any possible value.
let somePoint = (1, 1)
switch somePoint {
case (0, 0):
print("\(somePoint) is at the origin")
case (_, 0):
print("\(somePoint) is on the x-axis")
case (0, _):
print("\(somePoint) is on the y-axis")
case (-2...2, -2...2):
print("\(somePoint) is inside the box")
default:
print("\(somePoint) is outside of the box")
}
// Prints "(1, 1) is inside the box"
Value Bindings :
Aswitch
case can name the value or values it matches to temporary constants or variables, for use in the body of the case. This behavior is known as value binding, because the values are bound to temporary constants or variables within the case’s body.The example below takes an (x, y) point, expressed as a tuple of type(Int, Int)
, and categorizes it on the graph that follows:
let anotherPoint = (2, 0)
switch anotherPoint {
case (let x, 0):
print("on the x-axis with an x value of \(x)")
case (0, let y):
print("on the y-axis with a y value of \(y)")
case let (x, y):
print("somewhere else at (\(x), \(y))")
}
// Prints "on the x-axis with an x value of 2"
Where :
Aswitch
case can use awhere
clause to check for additional conditions.The example below categorizes an (x, y) point on the following graph:
let yetAnotherPoint = (1, -1)
switch yetAnotherPoint {
case let (x, y) where x == y:
print("(\(x), \(y)) is on the line x == y")
case let (x, y) where x == -y:
print("(\(x), \(y)) is on the line x == -y")
case let (x, y):
print("(\(x), \(y)) is just some arbitrary point")
}
// Prints "(1, -1) is on the line x == -y"
Compound Cases :
Multiple switch cases that share the same body can be combined by writing several patterns aftercase
, with a comma between each of the patterns. If any of the patterns match, then the case is considered to match. The patterns can be written over multiple lines if the list is long. For example:
let someCharacter: Character = "e"
switch someCharacter {
case "a", "e", "i", "o", "u":
print("\(someCharacter) is a vowel")
case "b", "c", "d", "f", "g", "h", "j", "k", "l", "m",
"n", "p", "q", "r", "s", "t", "v", "w", "x", "y", "z":
print("\(someCharacter) is a consonant")
default:
print("\(someCharacter) is not a vowel or a consonant")
}
// Prints "e is a vowel"
// Another example
let stillAnotherPoint = (9, 0)switch stillAnotherPoint {
case (let distance, 0), (0, let distance):
print("On an axis, \(distance) from the origin")
default:
print("Not on an axis")
}
// Prints "On an axis, 9 from the origin"
Control Transfer Statements :
Control transfer statements change the order in which your code is executed, by transferring control from one piece of code to another. Swift has five control transfer statements:continue
break
fallthrough
return
throw
Continue : The
continue
statement tells a loop to stop what it is doing and start again at the beginning of the next iteration through the loop. It says “I am done with the current loop iteration” without leaving the loop altogether.
Break :
Thebreak
statement ends execution of an entire control flow statement immediately. Thebreak
statement can be used inside aswitch
or loop statement when you want to terminate the execution of theswitch
or loop statement earlier than would otherwise be the case.Break in a Loop Statement
When used inside a loop statement,break
ends the loop’s execution immediately and transfers control to the code after the loop’s closing brace (}
). No further code from the current iteration of the loop is executed, and no further iterations of the loop are started.Break in a Switch Statement
When used inside aswitch
statement,break
causes theswitch
statement to end its execution immediately and to transfer control to the code after theswitch
statement’s closing brace (}
).Fallthrough :
In Swift,switch
statements don’t fall through the bottom of each case and into the next one. That is, the entireswitch
statement completes its execution as soon as the first matching case is completed. By contrast, C requires you to insert an explicitbreak
statement at the end of everyswitch
case to prevent fallthrough. Avoiding default fallthrough means that Swiftswitch
statements are much more concise and predictable than their counterparts in C, and thus they avoid executing multipleswitch
cases by mistake.
let integerToDescribe = 5
var description = "The number \(integerToDescribe) is"
switch integerToDescribe {
case 2, 3, 5, 7, 11, 13, 17, 19:
description += " a prime number, and also"
fallthrough
default:
description += " an integer."
}
print(description)
// Prints "The number 5 is a prime number, and also an integer."
Comments
Post a Comment