Switch case with range
This should work.
private func calculateUserScore() -> Int {
let diff = abs(randomNumber - Int(bullsEyeSlider.value))
switch diff {
case 0:
return PointsAward.bullseye.rawValue
case 1..<10:
return PointsAward.almostBullseye.rawValue
case 10..<30:
return PointsAward.close.rawValue
default:
return 0
}
}
It's there in the The Swift Programming Language book under Control Flow -> Interval Matching.
In case that you need to check if a value is bigger than any number or between 2 values use it is possible to use where
instead of if
looks a bit cleaner this will work
func isOutdated(days: Int) -> Outdated {
var outdatedStatus = Outdated.none
switch days {
case _ where days < 5:
outdatedStatus = .tooLow
case 5...10:
outdatedStatus = .low
case 11...20:
outdatedStatus = .high
case _ where days > 20:
outdatedStatus = .expired
default:
outdatedStatus = .none
}
return outdatedStatus
}
Only for you:
enum PointsAward: Int {
case close
case almostBullseye
case bullseye
}
private func calculateUserStory() -> Int {
let bullsEyeSliderValue = 9
let randomNumber = 100
let diff = abs(randomNumber - Int(bullsEyeSliderValue))
switch diff {
case 0:
return PointsAward.bullseye.rawValue
case 0..<10:
return PointsAward.almostBullseye.rawValue
case 0..<30:
return PointsAward.close.rawValue
default: return 0
}
}