Ternary Operators in Swift
Ternary operators are composed of 3 key parts—the condition, the value if true, and the value if false.
It also goes by the question mark colon operator
?:
Or you could call it the WTF operator (What ? True : False
)
Ternary operators can be used to cut down on the amount of code required. In the following example, a ternary operator can be used to customize a greeting for a user based on whether or not they are logged in.
An equivalent If Statement would look something like this.
Ternary Operators in SwiftUI
In the following example, a ternary operator is used to display a different message depending on whether a user is logged in.
This can also be achieved with Conditional Rendering and an If Statement.
The ternary operator is particularly useful when applying multiple modifiers on a view.
Compared to an equivalent If-Statement.
In These Collections
This article can also be found in these collections.