Swift Language Booleans and Inline Conditionals


Example

A clean way to handle booleans is using an inline conditional with the a ? b : c ternary operator, which is part of Swift's Basic Operations.

The inline conditional is made up of 3 components:

question ? answerIfTrue : answerIfFalse

where question is a boolean that is evaluated and answerIfTrue is the value returned if the question is true, and answerIfFalse is the value returned if the question is false.

The expression above is the same as:

if question {
    answerIfTrue
} else {
    answerIfFalse
}

With inline conditionals you return a value based on a boolean:

func isTurtle(_ value: Bool) {
    let color = value ? "green" : "red"
    print("The animal is \(color)")
}

isTurtle(true) // outputs 'The animal is green'
isTurtle(false) // outputs 'The animal is red'

You can also call methods based on a boolean value:

func actionDark() {
    print("Welcome to the dark side")
}

func actionJedi() {
    print("Welcome to the Jedi order")
}

func welcome(_ isJedi: Bool) {
    isJedi ? actionJedi() : actionDark()
}

welcome(true) // outputs 'Welcome to the Jedi order'
welcome(false) // outputs 'Welcome to the dark side'

Inline conditionals allow for clean one-liner boolean evaluations