Swift Booleans
Alongside strings and numbers, Swift has a very simple data type called a Boolean.
A Boolean stores only two values: true or false.
Booleans are named after George Boole, who studied logic.
🔹 Booleans in the Wild
You’ve already seen Booleans without realizing it:
let imageFile = "sakura.png"
print(imageFile.hasSuffix(".png"))
let petals = 120
print(petals.isMultiple(of: 3))
Both checks return either true or false.
🔹 Creating Booleans
Creating a Boolean works just like other types:
let isBlooming = true
let gameOver = false
You can also assign a Boolean from a condition:
let isSpecialFlower = petals.isMultiple(of: 3)
🔹 Flipping Booleans
Booleans don’t support math operators, but they do support logical operators.
The ! operator means “not”:
var isAuthenticated = false
isAuthenticated = !isAuthenticated
print(isAuthenticated)
isAuthenticated = !isAuthenticated
print(isAuthenticated)
This flips the value from false → true → false.
🔹 Using toggle()
Swift provides a cleaner way to flip Booleans using toggle():
var battleWon = false
print(battleWon)
battleWon.toggle()
print(battleWon)
This does the same thing as !, but reads better in real apps.
🌟 Wrap Up
Booleans represent yes/no, on/off, true/false decisions.
They power conditions, logic, and flow control🌸✨
Top comments (0)