Swift Conditions and Optionals
Conditions choose which code runs. Optionals let a value be missing safely.
if, else if and else
Swift does not need brackets around the condition, but the curly braces are required.
Example
let temperature = 34
if temperature > 40 {
print("Too hot, stay inside")
} else if temperature > 30 {
print("Hot, drink lots of water")
} else {
print("Nice weather")
}Hot, drink lots of water
switch
switch compares a value against many cases. In Swift:
- A
switchmust cover every possible value, so you often needdefault - There is no automatic fall-through and no
breakneeded - A case can match several values or a range
Example
let marks = 78
switch marks {
case 90...100:
print("Grade A+")
case 80..<90:
print("Grade A")
case 70..<80:
print("Grade B")
case 0..<70:
print("Keep working")
default:
print("Invalid marks")
}
let day = "Sunday"
switch day {
case "Saturday", "Sunday":
print("Weekend")
default:
print("Weekday")
}Grade B Weekend
| Range | Meaning |
|---|---|
90...100 | closed range: 90 to 100, including 100 |
80..<90 | half-open range: 80 to 89 |
What is an Optional?
Sometimes a value may not exist. A user may not have a middle name. Converting "abc" to a number fails. Swift uses an optional for this. An optional either holds a value or holds nil.
Add ? after a type to make it optional:
Example
var nickname: String? = nil
print(nickname ?? "No nickname")
nickname = "Aishu"
print(nickname ?? "No nickname")No nickname Aishu
?? is the nil-coalescing operator. It uses the value if there is one, and the default otherwise.
Unwrapping with if let
To use the value inside an optional, you must unwrap it. if let does this safely: the code runs only when the value is not nil.
Example
let input = "350"
if let price = Int(input) {
print("Price with tax: \(price + 50)")
} else {
print("That is not a number")
}
let phone: String? = nil
if let phone {
print("Calling \(phone)")
} else {
print("No phone number saved")
}Price with tax: 400 No phone number saved
if let phone is a short form of if let phone = phone, available since Swift 5.7.
guard let
guard checks a condition and leaves early if it fails. It keeps the main code less indented. It is common inside functions:
Example
func greet(_ name: String?) {
guard let name else {
print("Hello, guest")
return
}
print("Hello, \(name)")
}
greet("Hamza")
greet(nil)Hello, Hamza Hello, guest
Avoid force-unwrapping with ! (like nickname!). If the value is nil, your app crashes. Use if let, guard let or ?? instead.
Exercise
Exercise
What does print(Int("12a") ?? -1) print?
