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.
这篇关于带范围的开关盒的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:带范围的开关盒
基础教程推荐
- UIWebView 委托方法 shouldStartLoadWithRequest:在 WKWebView 中等效? 2022-01-01
- Kivy Buildozer 无法构建 apk,命令失败:./distribute.sh -m “kivy"d 2022-01-01
- 当从同一个组件调用时,两个 IBAction 触发的顺序是什么? 2022-01-01
- 如何在 UIImageView 中异步加载图像? 2022-01-01
- 如何让对象对 Cocos2D 中的触摸做出反应? 2022-01-01
- 如何在没有IB的情况下将2个按钮添加到右侧的UINavigationbar? 2022-01-01
- 如何在 iPhone 上显示来自 API 的 HTML 文本? 2022-01-01
- android 应用程序已发布,但在 google play 中找不到 2022-01-01
- Android:对话框关闭而不调用关闭 2022-01-01
- 在 gmail 中为 ios 应用程序检索朋友的朋友 2022-01-01