In Swift, we find traditional C-like if
-statements. We use "else if" after an if and follow up with an else block—this is standard.
The Swift language supports ternary statements and guard statements. And the "if let" syntax allows us to unwrap
a value easily.
This program uses an if
-statement. It tests the var
also with an else
-if and an else. The size is 10, so the else
-if part matches.
if
-statement.else
-if and else can be on the same line as the closing brace, or a newline. Either is accepted.var size = 10 // Test size var in if, else-if block. if size >= 20 { print("Big") } else if size >= 10 { print("Medium") } else { print("Small") }Medium
Swift supports a ternary statement. This uses a question mark after an initial condition. If the condition is true, the first value after the question mark is used.
Int
based on the argument to the test()
func
.func test(x: Int) { // Use a ternary statement. // Set y to 5 if x is 10. // ... Set it to 0 otherwise. let y = x == 10 ? 5 : 0 print(y) } // Call ternary test method. test(x: 10) test(x: 200)5 0
A constant can be introduced in an if
-statement. Here we use the "if let" construct to look up a value in a dictionary.
nil
) the inner statements of the if are reached. We can access the constant directly.nil
) the inner statements of the if are not reached.let animals = ["cat": 5, "dog": 2] // Execute inner block if constant is not nil. if let catCount = animals["cat"] { // This gives us a non-nil dictionary value. print(catCount) } if let birdCount = animals["bird"] { // The value is nil, so this is not reached. print(birdCount) } else { print(0) // Reached. }5 0
A bool
can store the result of an expression (one that evaluates to true or false). With an if
-statement, we can then test the bool
. This simplifies some programs.
even()
method in constant bools. We then test those constants against true and false.func even(left: Int, right: Int) -> Bool { // Return a bool if the two arguments are equal. return left == right } // Get a bool result. let even1 = even(left: 10, right: 20) if even1 == false { print("Sides not even") } // Use bool type. let even2: Bool = even(left: 40, right: 40) if even2 == true { print("Sides are even") }Sides not even Sides are even
This statement is like an if
-statement, but it must return or break
. It is used to validate arguments. It helps enforce a program's correctness at runtime.
Ifs are used in nearly every program. They encode simple condition tests better than switches. But switches allow more complex, detailed branches.