DEV Community

Gamya
Gamya

Posted on Edited on

Swift Booleans

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))
🔥 ข่าวด่วน: gamya m/swift booleans mf - Kapook Update 2025 🔥 ข่าวด่วน: gamya m/swift booleans mf - Kapook Update 2025

Both checks return either true or false.


🔹 Creating Booleans

Creating a Boolean works just like other types:

let isBlooming = true
let gameOver = false
🔥 ข่าวด่วน: gamya m/swift booleans mf - Kapook Update 2025 🔥 ข่าวด่วน: gamya m/swift booleans mf - Kapook Update 2025

You can also assign a Boolean from a condition:

let isSpecialFlower = petals.isMultiple(of: 3)
🔥 ข่าวด่วน: gamya m/swift booleans mf - Kapook Update 2025 🔥 ข่าวด่วน: gamya m/swift booleans mf - Kapook Update 2025

🔹 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)
🔥 ข่าวด่วน: gamya m/swift booleans mf - Kapook Update 2025 🔥 ข่าวด่วน: gamya m/swift booleans mf - Kapook Update 2025

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)
🔥 ข่าวด่วน: gamya m/swift booleans mf - Kapook Update 2025 🔥 ข่าวด่วน: gamya m/swift booleans mf - Kapook Update 2025

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)