It’s common to want modifiers that apply only when a certain condition is met, and in SwiftUI the easiest way to do that is with the ternary conditional operator.
As a reminder, to use the ternary operator you write your condition first, then a question mark and what should be used if the condition is true, then a colon followed by what should be used if the condition is false. If you forget this order a lot, remember Scott Michaud’s helpful mnemonic: What do you want to check, True, False, or “WTF” for short.
For example, if you had a property that could be either true or false, you could use that to control the foreground style of a button like this:
struct ContentView: View {
@State private var useRedText = false
var body: some View {
Button("Hello World") {
// flip the Boolean between true and false
useRedText.toggle()
}
.foregroundStyle(useRedText ? .red : .blue)
}
}
So, when useRedText
is true the modifier effectively reads .foregroundStyle(.red)
, and when it’s false the modifier becomes .foregroundStyle(.blue)
. Because SwiftUI watches for changes in our @State
properties and re-invokes our body
property, whenever that property changes the color will immediately update.
You can often use regular if
conditions to return different views based on some state, but this actually creates more work for SwiftUI – rather than seeing one Button
being used with different colors, it now sees two different Button
views, and when we flip the Boolean condition it will destroy one to create the other rather than just recolor what it has.
So, this kind of code might look the same, but it’s actually less efficient:
var body: some View {
if useRedText {
Button("Hello World") {
useRedText.toggle()
}
.foregroundStyle(.red)
} else {
Button("Hello World") {
useRedText.toggle()
}
.foregroundStyle(.blue)
}
}
Sometimes using if
statements are unavoidable, but where possible prefer to use the ternary operator instead.
GO FURTHER, FASTER Unleash your full potential as a Swift developer with the all-new Swift Career Accelerator: the most comprehensive, career-transforming learning resource ever created for iOS development. Whether you’re just starting out, looking to land your first job, or aiming to become a lead developer, this program offers everything you need to level up – from mastering Swift’s latest features to conquering interview questions and building robust portfolios.
Link copied to your pasteboard.