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"
Subscribe to continue reading
Get full access to this lesson and all 10 lessons in this course.