UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

SLOVED: Question: Ternary Operator vs Inline Closure

Forums > 100 Days of SwiftUI

@boat  

Hello,

I've done the 14 day fundalmentals, and on Day15 is the consolidation day, where Paul provided an one-hour quick review of what we've learned so far. https://www.hackingwithswift.com/articles/242/learn-essential-swift-in-one-hour

When I learned about Ternary for the first time, I haven't learned about closure, trailing closure or inline closure. But now I've learned them (spent lots of time re-watching these tutorials and did homework on my playground too) . I'm getting confused about when to use ternary and when to use trailing closure.

At 13'40" of the above one-hour class, Paul demonstrated again on ternary operator :

let age = 18
let canVote = age >= 18 ? "Yes" : "No"

I tried to turn the above into a closure:

let canVote = age {(number: Int) in if {number >= 18 print ("can vote")}}

I'm just wondering , terary is also kind of inline function , right ?
When to use ternary and when to use closure ?

thanks in advance,

Boat

2      

hi,

i would not over-think the ternary operator.

basically, writing

let canVote = age >= 18 ? "Yes" : "No"

is the same as writing

var canVote: String
if age >= 18 {
    canVote = "Yes"
} else {
    canVote = "No"
}

the ternary operator was part of the C language, designed over 50 years ago. there was no code completion or simple copy-paste back then, so a more condensed language syntax was appreciated by the programmer in writing the ternary with fewer keystrokes, in order to avoid having to write the longer if-else statement.

hope that helps,

DMG

2      

I agree with @delaware.

But let me add:

Up to now you've used ternary operators for simple descisions. Is the user over or under 18 years? Is the alarm on or off? Did the user enter an email address or not?

Yes, you could turn each of those into a function. But as @delaware noted, it would be lots of lines with unnecessary syntatic structures.

But take the last example. Did the user enter an email or not?

While this can be coded in a single line of code using a ternary operator, think of a larger example. For instance, Did the user enter all the required fields in the purchase order form?

While I suspect you could smash many ternary operations together, this would be madness. In this case, using ternary operations to make a complex programming descision is wrong. Here, you'll want the closure allowing you to execute many lines of logic to determine if the purchase order form is complete or not.

You'll have many tools in your Swift tool box. Ternary operators are small screwdrivers. They are also useful light switches when designing SwiftUI layouts. They are useful, but you can't use them on all the problems you'll encounter. Pick the right tool!

2      

Ternary operator come very important in SwiftUI when you want to change a modifier based on a condition, where if statement may have an impact on proformance.

From How to use the ternary conditional operator for quick tests

There’s one last way to check conditions in Swift, and when you’ll see it chances are you’ll wonder when it’s useful. To be fair, for a long time I very rarely used this approach, but as you’ll see later it’s really important with SwiftUI.

EG This is better as complier knows about the two colors at run time and only redraws that part of view

struct ContentView: View {
    @State var color = true

    var body: some View {
        ZStack {
            Color(color ? .red : .blue) // Ternary operator
                .ignoresSafeArea()

            Button("Change Color") {
                color.toggle()
            }
            .foregroundColor(.white)
            .buttonStyle(.borderedProminent)
        }
    }
}

then this as compler will redraw the whole view evert time.

struct ContentView: View {
    @State var color = true

    var body: some View {
        ZStack {
            if color { // With an if statement
                Color.red
                    .ignoresSafeArea()
            } else {
                Color.blue
                    .ignoresSafeArea()
            }

            Button("Change Color") {
                color.toggle()
            }
            .foregroundColor(.white)
            .buttonStyle(.borderedProminent)
        }
    }
}

Read this for more detail Conditional modifiers

2      

For the explanation about the why closures, I would simply say that Paul has written a good explanation here - Closures.

2      

EG This is better as complier knows about the two colors at run time and only redraws that part of view

Not only is this better for the compiler it's the recommended way from Apple to do it in SwiftUI.

2      

@boat  

Dear @delawaremathguy @Obelix @Greenamberred and @Hatsushir

Thank you so much for the input.

I rewatched and read what you've written for me, realizing that I had forgotten the most important context for the Tenary Operator, it's only for a "If" test, nothing else !

Thank you so mcuh

Boat

2      

Hacking with Swift is sponsored by RevenueCat

SPONSORED Take the pain out of configuring and testing your paywalls. RevenueCat's Paywalls allow you to remotely configure your entire paywall view without any code changes or app updates.

Learn more here

Sponsor Hacking with Swift and reach the world's largest Swift community!

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.