Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Switch case with range

I'm learning Swift and tried to program the game "Bullseye" from Ryan Wenderlich by my own before watching the videos.

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. 
}

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.

like image 521
John Doah Avatar asked Oct 05 '18 12:10

John Doah


3 Answers

This should work.

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
    }
}

It's there in the The Swift Programming Language book under Control Flow -> Interval Matching.

like image 138
Rakesha Shastri Avatar answered Nov 09 '22 12:11

Rakesha Shastri


In case that you need to check if a value is bigger than any number or between 2 values use it is possible to use where instead of if looks a bit cleaner this will work

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
}
like image 31
Alejandro L.Rocha Avatar answered Nov 09 '22 12:11

Alejandro L.Rocha


Only for you:

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
    }
}
like image 34
Vitaliy Rusinov Avatar answered Nov 09 '22 11:11

Vitaliy Rusinov