You are viewing a free preview of this lesson.
Subscribe to unlock all 10 lessons in this course and every other course on LearningBro.
Swift provides a variety of control flow statements including conditionals, loops, and early exits. This lesson covers if, guard, switch, for-in, while, and control transfer statements.
let temperature = 25
if temperature > 30 {
print("It's hot!")
} else if temperature > 20 {
print("It's pleasant.")
} else {
print("It's cool.")
}
Note: Conditions in Swift must be
Boolexpressions. Unlike C or JavaScript, there is no implicit conversion from numbers to booleans.
let mood = if temperature > 25 { "warm" } else { "cool" }
guard provides an early exit when a condition is not met:
func greet(name: String?) {
guard let name = name else {
print("No name provided.")
return
}
// 'name' is now a non-optional String
print("Hello, \(name)!")
}
Best Practice: Use
guardfor preconditions at the top of a function. The happy path stays unindented, making code easier to read.
Swift's switch is powerful and exhaustive:
let grade = "A"
switch grade {
case "A":
print("Excellent!")
case "B":
print("Good job!")
case "C":
print("Satisfactory")
case "D":
print("Needs improvement")
case "F":
print("Failing")
default:
print("Invalid grade")
}
Note: Swift
switchstatements do not fall through by default. There is no need forbreakat the end of each case.
let score = 85
switch score {
case 90...100:
print("A")
case 80..<90:
print("B")
case 70..<80:
print("C")
case 60..<70:
print("D")
default:
print("F")
}
let point = (2, 0)
switch point {
case (0, 0):
print("Origin")
case (_, 0):
print("On the x-axis")
case (0, _):
print("On the y-axis")
case (-2...2, -2...2):
print("Inside the box")
default:
print("Outside the box")
}
let anotherPoint = (1, -1)
switch anotherPoint {
case let (x, y) where x == y:
print("On the line x == y")
case let (x, y) where x == -y:
print("On the line x == -y")
case let (x, y):
print("Somewhere else at (\(x), \(y))")
}
let fruits = ["Apple", "Banana", "Cherry"]
for fruit in fruits {
print(fruit)
}
let ages = ["Alice": 30, "Bob": 25, "Charlie": 35]
Subscribe to continue reading
Get full access to this lesson and all 10 lessons in this course.