Title here
Summary here
Branching with if
and else
in Swift is straightforward.
import Foundation
// Here's a basic example.
if 7 % 2 == 0 {
print("7 is even")
} else {
print("7 is odd")
}
// You can have an `if` statement without an else.
if 8 % 4 == 0 {
print("8 is divisible by 4")
}
// Logical operators like `&&` and `||` are often
// useful in conditions.
if 8 % 2 == 0 || 7 % 2 == 0 {
print("either 8 or 7 are even")
}
// A statement can precede conditionals; any variables
// declared in this statement are available in the current
// and all subsequent branches.
let num = 9
if num < 0 {
print("\(num) is negative")
} else if num < 10 {
print("\(num) has 1 digit")
} else {
print("\(num) has multiple digits")
}
To run this Swift code, you can save it in a file (e.g., if_else.swift
) and execute it using the Swift command-line tool:
$ swift if_else.swift
7 is odd
8 is divisible by 4
either 8 or 7 are even
9 has 1 digit
Note that you don’t need parentheses around conditions in Swift, but the braces are required.
Swift also provides a ternary conditional operator ?:
, which can be used for simple conditional expressions. However, for more complex conditions, it’s generally better to use a full if
statement for clarity.