DEV Community

Gamya
Gamya

Posted 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))
Enter fullscreen mode Exit fullscreen mode

Both checks return either true or false.


🔹 Creating Booleans

Creating a Boolean works just like other types:

let isBlooming = true
let gameOver = false
Enter fullscreen mode Exit fullscreen mode

You can also assign a Boolean from a condition:

let isSpecialFlower = petals.isMultiple(of: 3)
Enter fullscreen mode Exit fullscreen mode

🔹 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)
Enter fullscreen mode Exit fullscreen mode

This flips the value from falsetruefalse.


🔹 Using toggle()

Swift provides a cleaner way to flip Booleans using toggle():

var battleWon = false
print(battleWon)

battleWon.toggle()
print(battleWon)
Enter fullscreen mode Exit fullscreen mode

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)