Code a condition in a range of values


I wish to display a status punt according conditions.

  • We've got a slider :
    this slider send us a fixed value.
    (min 0, max :1)

  • we've got a sound amplitude witch vary a little:
    I wish to show 3 status ( Red, Orange, Green )

Red if slider value is over min_amp
Orange if slider is in this range between self.minAmp-0,01 and self.minAmp-0,08
Green if slider is below this range.
how code it in swift? Thanks to help a newbie

I'm assuming it's okay if it's red if slider value is exactly equal to min amp

enum Status {
    case red
    case orange
    case green

func getStatus(sliderValue: Double, minAmp: Double) -> Status {
    switch sliderValue {
    case minAmp...:
        return .red
    case (minAmp-0.08)...(minAmp-0.01):
        return .orange
    case ...(minAmp-0.08):
        return .green
        fatalError("I haven't provided info in my forum post about what to do in this case")

print(getStatus(sliderValue: 10, minAmp: 0)) // red
print(getStatus(sliderValue: -0.005, minAmp: 0)) // fatal error

the ... syntax is a range. If a number is only on one side, the other side isn't bounded. Number is in the range if it's equal or higher than the number on the left side, and equal or lower than the number on the right side. If the number matches multiple cases in the switch, it falls into the first matching one. If it doesn't match any, then it falls into the default.

1 Like

oh great, thats exactly what I need. the switch statement is powerful.

dont we need for green status to put the check on :

Thanks a lot for your help, its working fine, even MinAmp drop below slider value.

1 Like