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))
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 false โ†’ true โ†’ false.


๐Ÿ”น 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)