Switch case with range(带范围的开关盒)
问题描述
我正在学习 Swift,并在观看视频之前尝试自己编写 Ryan Wenderlich 的游戏Bullseye".
I'm learning Swift and tried to program the game "Bullseye" from Ryan Wenderlich by my own before watching the videos.
我需要根据他与目标数字的接近程度来给用户积分.我试图计算差异,然后检查范围并给用户分数,这就是我用 If-else 所做的(不能用 switch case 做):
I needed to give the user points depending on how close to the target number he was. I tried to calculate the difference and than check the range and give the user the points, This is what I did with If-else (Couldn't do it with 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 会给我一条错误消息.
Is there a way to do it more elegantly or with Switch-Case?
I couldn't just do diff == 0
for example in the case in switch case as xCode give me an error message.
推荐答案
这应该可行.
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
}
}
它在 The Swift Programming Language 一书中控制流下-> 区间匹配.
It's there in the The Swift Programming Language book under Control Flow -> Interval Matching.
这篇关于带范围的开关盒的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:带范围的开关盒


基础教程推荐
- 固定小数的Android Money Input 2022-01-01
- LocationClient 与 LocationManager 2022-01-01
- “让"到底是怎么回事?关键字在 Swift 中的作用? 2022-01-01
- Android文本颜色不会改变颜色 2022-01-01
- 如何使 UINavigationBar 背景透明? 2022-01-01
- :hover 状态不会在 iOS 上结束 2022-01-01
- 在 iOS 上默认是 char 签名还是 unsigned? 2022-01-01
- 使用 Ryzen 处理器同时运行 WSL2 和 Android Studio 2022-01-01
- Android ViewPager:在 ViewPager 中更新屏幕外但缓存的片段 2022-01-01
- 如何使用 YouTube API V3? 2022-01-01