zardon
zardon

Reputation: 1651

Swift - Get dictionary value where key is an enum

I'm writing a quick game and want to write a list of target goals for short, medium and long game. This is just a linear list of goals for cash.

enum GameLength : Int {
    case ShortGame
    case MediumGame
    case LongGame

    static let allValues = [
        GameLength.ShortGame.rawValue,
        GameLength.MediumGame.rawValue,
        GameLength.LongGame.rawValue,
        ]
}

struct GameGoal {

// I think this should be a set as the game lengths cannot repeat
        var cashGoals = [ [GameLength.ShortGame: 100] ,
                          [GameLength.MediumGame: 200] ,
                          [GameLength.LongGame: 300] ]


    func target(gameLength:GameLength) {
        var result = cashGoals[gameLength].first
        print (result)
    }
}

var gameLength:GameLength = .MediumGame
var gameGoal = GameGoal().target(gameLength)

print (gameGoal)

The problem here is that I can't seem to now access the value for the given target.

Ideally, I want to map the gameLength enum with a value.

The reason why they are separated is because I need to apply a weighting to the cash goal later on.

Perhaps I'm over complicating the issue.

But regardless;

Question > How do I access the dictionary where the key is an enum, and only get the first enum that matches the value

Upvotes: 1

Views: 1918

Answers (2)

twiz_
twiz_

Reputation: 1198

cashGoals as declared here is not a dictionary. It is an array of dictionaries with one key:value each. Ditch the internal [ ] and you can subscript with your enum. Also, as of swift 3 the convention is to use lower case for enum cases.

var cashGoals: [GameLength: Int] = [.shortGame: 100 ,
                                    .mediumGame: 200 ,
                                    .longGame: 300 ]
print(cashGoals[.shortGame]) // 100
print(GameLength.shortGame.rawValue) // 0 

You could also just make the raw value of the enum the Int you need, but maybe you want to keep the game length and the cash goal as separate pieces of data so that you can vary the cash goal for each length.. you could not change the enum rawValue, but you could change the struct's variable.

Upvotes: 1

Bek
Bek

Reputation: 2226

You can actually set the raw values of your enumerations so that you don't have to deal with that dictionary at all.

enum GameLength : Int {
    case ShortGame = 100
    case MediumGame = 200
    case LongGame = 300
}

Then you can access it through gameLength.rawValue

Upvotes: 2

Related Questions