Operators and Control Flow
if and else work as you'd expect from any C-family language — a condition, no parentheses required, followed by a block. for-in iterates over a range or any collection directly, with no separate index variable to manage.
let score = 73
if score >= 60 {
print("pass")
} else {
print("fail")
}
for i in 1...3 {
print(i, terminator: " ")
}
print()pass 1 2 3
1...3 is a closed range — it includes both endpoints. print(i, terminator: " ") is Swift's way of printing without a trailing newline, since print() adds one by default.
switch with ranges
Swift's switch can match against ranges directly, and — unlike Java's or C#'s switch — it doesn't fall through to the next case by default, so no break statement is needed.
let grade = 85
switch grade {
case 90...100:
print("A")
case 80..<90:
print("B")
default:
print("C or below")
}B
80..<90 is a half-open range — it includes 80 but excludes 90. Next: functions — defining functions, parameters, and default argument values.
Practice exercise
Given a constant score set to 73, print "pass" if score is 60 or greater, otherwise print "fail".