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.
这篇关于带范围的开关盒的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:带范围的开关盒


基础教程推荐
- 如何从 logcat 中删除旧数据? 2022-01-01
- 通过重定向链接在 Google Play 中打开应用 2022-01-01
- NSString intValue 不能用于检索电话号码 2022-01-01
- navigator.geolocation.getCurrentPosition 在 Android 浏览器上 2022-01-01
- Android:getLastKnownLocation(LocationManager.NETWORK_PROVIDER 2022-01-01
- iPhone - 获取给定地点/时区的当前日期和时间并将其与同一地点的另一个日期/时间进行比较的正确方法 2022-01-01
- Cocos2d iPhone 非矩形精灵触摸检测 2022-01-01
- AdMob 广告未在模拟器中显示 2022-01-01
- libGDX 从精灵或纹理中获取像素颜色 2022-01-01
- iOS4 创建后台定时器 2022-01-01