带范围的开关盒

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.

这篇关于带范围的开关盒的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:带范围的开关盒

基础教程推荐