Swift Operators
An operator is a sign that compares values or combines truth values. A comparison gives true or false as its result.
Comparing numbers
Each comparison prints true or false. The signs read as plain questions about the two numbers.
print(7 > 3)
print(7 == 3)
print(7 != 3)Comparing strings
String equality needs an exact match of every character. Letter order decides which string sorts first.
print("apple" == "apple")
print("apple" < "banana")
print("apple" > "banana")Combining truth values
Two stored Bool values feed both signs here. Each print shows the combined answer for its sign.
let sunny = true
let warm = false
print(sunny && warm)
print(sunny || warm)Flipping a Bool value
The ! sign sits before the variable name in the first print. The second print shows the stored value with no flip.
let ready = false
print(!ready)
print(ready)Picking a value with ?:
The ternary sign tests a condition first. It picks the value before the colon when the test is true and the value after the colon when the test is false.
let age = 20
print(age >= 18 ? "adult" : "minor")Example
let score = 75
let passed = score >= 50
print(passed && score < 100)
print(!passed || score == 75)Key points
- == checks whether two values are equal and != checks whether they differ.
- < and > compare size, and <= and >= allow equality as well.
- Strings compare in alphabetical order with the same signs.
- && gives true only when both sides are true.
- || gives true when at least one side is true.
- ! before a Bool value flips true to false and false to true.
- The ternary ?: picks one of two values based on a condition.
In this example, score holds 75 and passed holds true because score >= 50 is true. The first print joins passed and score < 100 with && and shows true. The second print flips passed with ! and joins it with score == 75 using ||, and shows true because the right side is true.
Try it Yourself
Edit the code, then press Run.
Running is simulated ยท Programiz Swift Compiler
Exercise
What prints when a program prints 5 <= 5?