2

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
  • I assume it is simplified example. Would you show more real code/part of what do you try to achieve, alternates might depend on input? Commented Jul 8, 2020 at 10:58

1 Answer 1

2

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

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

1 Comment

Thanks for the reply, that is one option that I have taken in my current code. I was almost hoping that SwiftUI 2.0 would have some way to switch on modifiers, rather than switching in Views. I think going for a custom helper function might be the best option at this stage. Much appreciated Sir.

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.