Change background color based on SWITCH statement

Hi,


I have this code to change my background color based on the enum AddressType


enum AddressType: String, CaseIterable{
  case shipFrom = "1"
  case shipTo = "2"
  case unknown = "999"

  init(type: String) {
  switch type {
  case "1": self = .shipFrom
  case "2": self = .shipTo
  default: self = .unknown
  }
  }

  var text: String {
  switch self {
  case .shipFrom: return "Ship From"
  case .shipTo: return "Ship To"
  case .unknown: return "N/A"
  }
  }
}


.background(addressType.self == AddressType.shipFrom ? Color.green : Color.yellow)


Question is now: what do I have to do if I want my shipFrom in Color.green and my shipTo in Color.orange? I have tried adding a 2nd .background() for the shipTo but that did not work.


Is there any way to work with more than 1 IF clause?


Max

Answered by Jim Dovey in 403193022

The way to use more logic in making the background color decision is to factor it out into another method:


private func backgroundColor(for addressType: AddressType) -> Color {
    switch (addressType) {
    case .shipFrom: return .green
    case .shipTo: return .orange
    case .unknown: return .yellow
    }
}

...

var body: some View {
    ...
    .background(backgroundColor(for: addressType))
}


Personally, I'd be inclined to put the color choice into the AddressType itself, perhaps in an extension available to the view that needs it:


extension AddressType {
    var backgroundColor: Color {
        switch (self) {
        case .shipFrom: return .green
        case .shipTo: return .orange
        case .unknown: return .yellow
        }
    }
}

...

.background(addressType.backgroundColor)
Accepted Answer

The way to use more logic in making the background color decision is to factor it out into another method:


private func backgroundColor(for addressType: AddressType) -> Color {
    switch (addressType) {
    case .shipFrom: return .green
    case .shipTo: return .orange
    case .unknown: return .yellow
    }
}

...

var body: some View {
    ...
    .background(backgroundColor(for: addressType))
}


Personally, I'd be inclined to put the color choice into the AddressType itself, perhaps in an extension available to the view that needs it:


extension AddressType {
    var backgroundColor: Color {
        switch (self) {
        case .shipFrom: return .green
        case .shipTo: return .orange
        case .unknown: return .yellow
        }
    }
}

...

.background(addressType.backgroundColor)

Excellent answer, thanks for providing both alternatives! 🙂


Max

Change background color based on SWITCH statement
 
 
Q