Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

184
Views
How do I conditionally format SwiftUI code
if(user.reserved == "yes") {
        HStack {
            Image(systemName: "person.crop.circle.badge.checkmark").foregroundColor(.green)
            
            Text("\(user.name)").foregroundColor(.green)
        }
    } else if (user.reserved == "no"){
        HStack {
            Image(systemName: "person.crop.circle.badge.checkmark").foregroundColor(.red)
            
            Text("\(user.name)").foregroundColor(.red)
        }
    } else if (user.reserved == "waiting") {
        HStack {
            Image(systemName: "person.crop.circle.badge.checkmark").foregroundColor(.orange)
            
            Text("\(user.name)").foregroundColor(.orange)
        }
    }

'''

I have this code where I want to change the appearance of the text color based on a user saying yes or no. I tried creating a var like "var color: Color" in the if statements however, it kept saying that it dit not conform to the view. How can I make conditional code effectively instead of having to copy past every thing again and again?

over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

You could use a computed property that returns a Color based on the user's reserved property:

struct User {
    var reserved : String
    var name : String
}

struct ContentView: View {
    @State private var user = User(reserved: "waiting", name: "Bob")
    
    var colorForReserved : Color {
        switch user.reserved {
        case "yes":
            return .green
        case "no":
            return .red
        case "waiting":
            return .orange
        default:
            return .black
        }
    }
    
    var body: some View {
        HStack {
            Image(systemName: "person.crop.circle.badge.checkmark")
            Text(user.name)
        }
        .foregroundColor(colorForReserved)
    }
}

Note that you can avoid the default if you changed reserved to an enum rather than a String

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!