我正在学习 Swift,并在观看视频之前尝试自己编写 Ryan Wenderlich 的游戏“Bullseye”。
我需要根据用户与目标数字的接近程度来给他分数。我尝试计算差异,然后检查范围并向用户提供分数,这就是我使用 If-else 所做的(无法使用 switch case 做到这一点):
private func calculateUserScore() -> Int {
let diff = abs(randomNumber - Int(bullsEyeSlider.value))
if diff == 0 {
return PointsAward.bullseye.rawValue
} else if diff < 10 {
return PointsAward.almostBullseye.rawValue
} else if diff < 30 {
return PointsAward.close.rawValue
}
return 0 // User is not getting points.
}
有没有更优雅的方法或者使用 Switch-Case? 我不能只做
diff == 0
,例如在 switch case 中,因为 xCode 给了我一条错误消息。
这应该有效。
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
}
}
where
而不是
if
看起来更干净,这会起作用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
}
在 Swift 5.9 新功能发布后,这可能会变得更简单:
func isOutdated(days: Int) -> Outdated {
switch days {
case _ where days < 5:
.tooLow
case 5...10:
.low
case 11...20:
.high
case _ where days > 20:
.expired
default:
.none
}
}
switch diff {
case 0:
print("Bull Eye")
case 1..<10:
print("Almost Bull Eye")
case 10..<30:
print("Close")
default:
print("Too Far")
}
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
}
}
a...b
// 范围从a到b,意味着b也包含在内
a..<b
// 范围从a到b-1,表示不包括b
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 } }
var progress: CGFloat!
switch CGFloat(progress) {
case 0 ... 0.25:
barColor = .red
case 0.25 ... 0.5:
barColor = .yellow
default:
break
}