Booleans and Inline Conditionals
suggest changeOne way to handle booleans is the a ? b : c ternary operator, which is part of Swift’s basic operators.
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 keep a boolean choice to a single expression.
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents