我有六个这样的代码块,我想缩短它们,同时仍然让它们有效地工作。这段代码按照我想要的方式工作,但是实在太大了。
let strStatResult = strStat
strengthModLabel.text = String(strStatResult)
switch strStatResult {
case let strStatResult where strStatResult == 1:
strengthModLabel.text = "-5"
case let strStatResult where strStatResult == 2 || strStatResult == 3:
strengthModLabel.text = "-4"
case let strStatResult where strStatResult == 4 || strStatResult == 5:
strengthModLabel.text = "-3"
case let strStatResult where strStatResult == 6 || strStatResult == 7:
strengthModLabel.text = "-2"
case let strStatResult where strStatResult == 8 || strStatResult == 9:
strengthModLabel.text = "-1"
case let strStatResult where strStatResult == 10 || strStatResult == 11:
strengthModLabel.text = "0"
case let strStatResult where strStatResult == 12 || strStatResult == 13:
strengthModLabel.text = "+1"
case let strStatResult where strStatResult == 14 || strStatResult == 15:
strengthModLabel.text = "+2"
case let strStatResult where strStatResult == 16 || strStatResult == 17:
strengthModLabel.text = "+3"
case let strStatResult where strStatResult == 18 || strStatResult == 19:
strengthModLabel.text = "+4"
case let strStatResult where strStatResult == 20 || strStatResult == 21:
strengthModLabel.text = "+5"
case let strStatResult where strStatResult == 22 || strStatResult == 23:
strengthModLabel.text = "+6"
case let strStatResult where strStatResult == 24 || strStatResult == 25:
strengthModLabel.text = "+7"
case let strStatResult where strStatResult == 26 || strStatResult == 27:
strengthModLabel.text = "+8"
case let strStatResult where strStatResult == 28 || strStatResult == 29:
strengthModLabel.text = "+9"
case let strStatResult where strStatResult == 30:
strengthModLabel.text = "+10"
default:
strengthModLabel.text = "Error"
}
我想过使用for循环或while循环来缩短它,但我不确定如何在缩短代码的同时实现它。
结果似乎是strStatResult / 2 - 5
。这适用于整数除法。10/2和11/2都是5。减去5得到0,就像你的巨大的switch语句。
假设strStatResult
是Int
(或其他整数类型),您所需要的是:
if strStatResult < 1 || strStatResult > 30 {
strengthModLabel.text = "Error"
} else {
let num = strStatResult / 2 - 5
strengthModLabel.text = num > 0 ? "+(num)" : "(num)"
}