2
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?

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you so much!! Couldn’t figure out how to get the if statements going.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.