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.
let isUserLoggedIn: Bool = true
let greeting = isUserLoggedIn ? "Welcome Back!" : "Please log in."
An equivalent If Statement would look something like this.
let isUserLoggedIn: Bool = true
let greeting: String
if isUserLoggedIn {
greeting = "Welcome Back!"
} else {
greeting = "Please log in."
}
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.
struct ContentView: View {
@State private var isUserLoggedIn = false
var body: some View {
Text(isUserLoggedIn ? "Welcome back!" : "Please log in.")
}
}
This can also be achieved with Conditional Rendering and an If Statement.
struct ContentView: View {
var body: some View {
if userIsLoggedIn {
Text("Welcome back!")
} else {
Text("Please log in.")
}
}
}
The ternary operator is particularly useful when applying multiple modifiers on a view.
struct ContentView: View {
@State private var isUserLoggedIn = false
var body: some View {
Text(isUserLoggedIn ? "Welcome back!" : "Please log in.")
.fontWeight(.heavy)
.fontDesign(.rounded)
}
}
Compared to an equivalent If-Statement.
struct ContentView: View {
var body: some View {
if userIsLoggedIn {
Text("Welcome back!")
.fontWeight(.heavy)
.fontDesign(.rounded)
} else {
Text("Please log in.")
.fontWeight(.heavy)
.fontDesign(.rounded)
}
}
}