Home > OS >  Switch statement for category selection and output
Switch statement for category selection and output

Time:10-08

So I have this part in my code, where I will have to create like 14 if/else conditionals, so I wanted to see if someone knows a better way for me to handle a Image render with multiple conditions.

So this is what I have:

if placeC.places[0].category == "Route" {
    Image("map-pin")
        .renderingMode(.template)
        .resizable()
        .frame(width: 35, height: 35)
        .foregroundColor(placeC.places[0].show ? .red : Color.init(UIColor(hexString: "#6A798E")))
        .onTapGesture {
            if !placeC.places[0].show {
                tapOnMapAnnotation(
                    place: placeC.places[0]
                )
            }
        }
        .overlay(
            Awesome.Image(icon: Awesome.Solid.route)
                .size(12)
                .foregroundColor(.white)
                .padding(.bottom, 15)
        )
} else if placeC.places[0].category == "Scenic Area" {
    Image("map-pin")
        .renderingMode(.template)
        .resizable()
        .frame(width: 35, height: 35)
        .foregroundColor(placeC.places[0].show ? .red : Color.init(UIColor(hexString: "#006994")))
        .onTapGesture {
            if !placeC.places[0].show {
                tapOnMapAnnotation(
                    place: placeC.places[0]
                )
            }
        }
        .overlay(
            Awesome.Image(icon: Awesome.Solid.binoculars)
                .size(12)
                .foregroundColor(.white)
                .padding(.bottom, 15)
        )
     etc...

Everything is the same, except the category and the hexString: "----" - How would I be able to utilize a function or possible a switch statement on this?

CodePudding user response:

You can abstract it into

func hexStringForCategory(_ category: String) -> String {
  switch category {
    case "Route":
      return "#6A798E"
    case "Scenic Area":
      return "_DIFFERENT_COLOR_"
    //etc..
    default:
      return "#FFFFFF"
  }
}

@ViewBuilder func viewForPlace(_ place: Place) -> some View {
  Image("map-pin")
        .renderingMode(.template)
        .resizable()
        .frame(width: 35, height: 35)
        .foregroundColor(place.show ? .red : Color.init(UIColor(hexString: hexStringForCategory(place.category))))
        .onTapGesture {
            if !place.show {
                tapOnMapAnnotation(
                    place: place
                )
            }
        }
        .overlay(
            Awesome.Image(icon: Awesome.Solid.route)
                .size(12)
                .foregroundColor(.white)
                .padding(.bottom, 15)
        )
}

Then, you could just call:

viewForPlace(placeC.places[0])

If you're only ever going to do this for placeC.places[0], you don't even need the second function -- you can just use the first.

  • Related