Ternary Operator in SwiftUI

Ternary Operator in SwiftUI

A summary of use cases of the ternary operators in SwiftUI

·

4 min read

The ternary operator is a shorthand way of writing an if-else statement in a single line of code. It is a powerful tool for simplifying code and improving readability. In SwiftUI, the ternary operator is commonly used to conditionally render views or modify view properties based on a boolean value. In this blog post, we will explore some use cases of the ternary operator in SwiftUI.

The code in this blog is available here.

Use Case 1: Conditional Rendering of Views

One of the most common use cases of the ternary operator in SwiftUI is for conditional rendering of views. For example, if we want to render a view conditionally based on a boolean value, we can use the ternary operator like this:

    struct ContentView1: View {
        @State var isLogin = false

        var body: some View {
            if isLogin {
                Text("Welcome back!")
            } else {
                Text("Please log in.")
            }

            // Using ternary operator
            isLogin ? Text("Welcome back!") : Text("Please log in.")
        }
    }

When the value of isLogin remains false:

When the value of isLogin is true:

Use Case 2: Toggling a Boolean Value

Another use case of the ternary operator is to toggle a boolean value. For example, if we want to toggle a boolean value when a button is pressed, we can use the ternary operator like this:

    struct ContentView2: View {
        @State var isOn = false

        var body: some View {
            Button(action: {
                isOn.toggle()
            }) {
                Text(isOn ? "ON" : "OFF")
            }
            .foregroundColor(.white)
            .bold()
            .frame(width: 150, height: 40)
            .background(Color.indigo.cornerRadius(5))
        }
    }

The text label of the button gets toggle every time the button is tapped.

Use Case 3: Modifying View Properties

The ternary operator can also be used to modify view properties conditionally. For example, if we want to change the color of a text view based on a boolean value, we can use the ternary operator like this:

    struct ContentView3: View {
        @State var isHighlighted = false

        var body: some View {
            Text("Tap me to highlight.")
                .bold()
                .foregroundColor(isHighlighted ? .red : .black)
                .onTapGesture {
                    isHighlighted.toggle()
                }
        }
    }

This use case is commonly used. You can not only use a ternary operator for a conditional style view modifier but also provide a sizing view modifier (such as a frame, corner radius etc) accordingly.

Use Case 4: Setting View Layouts

The ternary operator can also be used to set view layouts conditionally. For example, if we want to set the layout of a stack view based on a boolean value, we can use the ternary operator like this:

    struct ContentView4: View {
        var isVertical: Bool

        var body: some View {
            VStack {
                if isVertical {
                    vertical
                } else {
                    horizontal
                }

                // Using ternary operator
                isVertical ? AnyView(vertical) : AnyView(horizontal)
            }
        }
        var horizontal: some View {
            HStack {
                Text("Horizontal Stack")
                Text("Horizontal Stack")
            }
        }
        var vertical: some View {
            VStack {
                Text("Vertical Stack")
                Text("Vertical Stack")
            }
        }
    }

Note that both values we provided the ternary operator with must be of the same type, therefore, if the layout types are different (ex. HStack vs VStack in the example above), we can simply wrap the view with AnyView to make them the same type.

To see the result of the code above, we can declare two ContentView4s and pass true and false respectively.

                ContentView4(isVertical: true)
                ContentView4(isVertical: false)

You can see the first view presents texts in a VStack while the second view presents texts in an HStack.

In conclusion, the ternary operator is a powerful tool for simplifying code and improving readability in SwiftUI. Its ability to conditionally render views, toggle boolean values, modify view properties, and set view layouts make it an essential part of any SwiftUI developer's toolkit.

That’s all of today’s post. I hope it helps and let me know if it is by leaving a comment. Don’t forget to subscribe to my newsletter if you’d like to receive posts like this via email.

I’ll see you in the next post!