Modifying SwiftUI Views based on non-binary data / conditions?

Viewed 38

Question: I have a fairly large SwiftUI View that adds a country code based on my model data. My feeling is that I should extract a subview and then pass the country code in, then use a switch, but I just wanted to check I was not missing something and making this too complicated.

SwiftUI has a very nice method of dealing with two possible options based on a Bool, this is nice as it modifies a single View.

struct TestbedView_2: View {
    var isRed: Bool
    var body: some View {
        Text("Bilbo").foregroundColor(isRed ? Color.red : Color.blue)
    }
}

If on the other hand your model presents a none binary choice you can use a switch statement. This however returns an Independent View based on the case selected resulting in duplicate code.

struct TestbedView_3: View {
    var index: Int
    var body: some View {
        switch(index) {
            case 1:
                Text("Bilbo").foregroundColor(Color.red)
            case 2:
                Text("Bilbo").foregroundColor(Color.green)
            default:
                Text("Bilbo").foregroundColor(Color.blue)
        }
    }
}
1 Answers

Here is more clean approach:

  1. Only display text once - use function to get the color
Text("Bilbo").foregroundColor(self.getColor(index))
  1. Create the getColor function
private func getColor(_ index : Int) -> Color {        
    switch index {
    case 1: return Color.red
    case 2: return Color.green
    case 3: return Color.blue
    default: return Color.clear
    }
}

NOTE: I am using Color.clear as default case in the switch statement since it must be present

Related