我创建了下面的switch语句,根据我在weightType中输入的字符串返回Double值。
我想用Enum代替它,以便它更灵活。我虽然这是一个很容易的改变,但我已经尝试了各种各样的东西,但我无法使它发挥作用。
有人可以帮帮我吗? THX!
var weightType: String = "kettlebell"
func returnWeightLimit() -> Double {
switch weightType {
case "barbell": return(132.0)
case "kettlebell": return(70.5)
case "dumbbell": return(115.0)
default: return(0.0)
}
}
let weightLimit = returnWeightLimit()
答案 0 :(得分:0)
使用原始值支持的枚举:
enum WeightType: String {
case barbell
case kettlebell
case dumbbell
var weightLimit: Double {
switch self {
case .barbell: return 132.0
case .kettlebell: return 70.5
case .dumbbell: return 115.0
default: return 0
}
}
}
示例:
let str = "kettlebell"
if let weightType = WeightType(rawValue: str) {
print(weightType.weightLimit)
} else {
print("You provided the wrong rawValue")
}