NEW: Nominations are now open for the 2019 Swift Community Awards! >>

Conditional modifiers

Paul Hudson    @twostraws   

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 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.

For example, if you had a property that could be either true or false, you could use that to control the foreground color 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
        .foregroundColor(useRedText ? .red : .blue)

So, when useRedText is true the modifier effectively reads .foregroundColor(.red), and when it’s false the modifier becomes .foregroundColor(.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 sometimes use regular if conditions to return different views based on some state, but this is only possible in a handful of cases.

For example, this kind of code isn’t allowed:

var body: some View {
    if self.useRedText {
        return Text("Hello World")
    } else {
        return Text("Hello World")

Remember, some View means “one specific type of View will be returned, but we don’t want to say what.” Because of the way SwiftUI creates new views using generic ModifiedContent wrappers, Text(…) and Text(…).background( are different underlying types and that isn’t compatible with some View.

SAVE 20% ON iOS CONF SG The largest iOS conference in Southeast Asia is back in Singapore for the 5th time in January 2020, now with two days of workshops plus two days of talks on SwiftUI, Combine, GraphQL, and more! Save a massive 20% on your tickets by clicking on this link.

Buy Testing Swift Buy Practical iOS 12 Buy Pro Swift Buy Swift Design Patterns Buy Swift Coding Challenges Buy Server-Side Swift (Vapor Edition) Buy Server-Side Swift (Kitura Edition) Buy Hacking with macOS Buy Advanced iOS Volume One Buy Advanced iOS Volume Two Buy Hacking with watchOS Buy Hacking with tvOS Buy Hacking with Swift Buy Dive Into SpriteKit Buy Swift in Sixty Seconds Buy Objective-C for Swift Developers Buy Beyond Code

Was this page useful? Let us know!

Average rating: 4.8/5