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

Help with Views and Modifiers > Day 24 > Challenge 2

Forums > 100 Days of SwiftUI

Challenge #2 states:

Go back to project 1 and use a conditional modifier to change the total amount text view to red if the user selects a 0% tip.

I accomplished this by doing the following:

Section(header: Text("Total check amount, including tip:")) {
                    Text("$\(checkWithTip, specifier: "%.2f")")
                }
                .foregroundColor((tipPercentages[tipPercentage] != 0) ? .black : .red)

While the solution I stumbled into seems to be working, is it following best practices? I tried to use something like @State private var tipColor = false with tipColor in my ternary operator, but I couldn't figure out how to toggle it...

3      

I have the same problem, how/where would you toggle an @State property that you can then use to achieve the same result?

3      

Make computed proprty that return a Bool

var tipColor: Bool {
  tipPercentages[tipPercentage] == 0
}

then use this in modiflier

.foregroundColor(tipColor ? .red : .black)

You do not need @State as @State private var tipPercentage = 0 and therefore it looking for any changes to that and will update anything it need to.

PS used == instead of!= as this is less likely to miss and clearer to someone who reads your code.

4      

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.