Fredrik L Fredrik L - 4 months ago 9
iOS Question

iOS Swift access string in array

I set up an array like this:

let modelArray = [
"Casual": ["health": 17, "weapon": 8, "crafting": 15, "social": 30],
"Soldier": ["health": 25, "weapon": 32, "crafting": 8, "social": 5],
"Doctor": ["health": 35, "weapon": 5, "crafting": 15, "social": 15],
"Dorothy": ["health": 15, "weapon": 15, "crafting": 20, "social": 20],
"Asian": ["health": 13, "weapon": 5, "crafting": 7, "social": 45],
"Police": ["health": 23, "weapon": 22, "crafting": 5, "social": 20]
]


How do I access the String (for example "Casual") value when looping?

for (index, model) in character.modelArray.enumerate()
{
print("\(index) carries: \(model[0]")
}


This gives me Type '(String, Dictionary)' has no subscript members

Answer

As Josh points out, your modelArray object is an array which contains dictionary types. (let modelArray : [String: [String:Int]] is the full type information).

The dictionary within can't be subscripted using an Int, only a String.

Here's a version of your code, which will get some the health stat of each character:

for statDictionary in characters.modelArray {
    let health = statDictionary["health"]
    print(health)
}

further suggestion

Storing data like this in a dictionary is fine for some purposes, but you may find a cleaner, safer API can be made by creating structs (or classes) for holding this state information.

struct CharacterStats {
     let health : Int
     let weaponNumber : Int
    // etc.
}

Then enumerating would be even simpler and require no loose string keys (which could be mistyped).

 for stat in characters {
     let health = stat.health
}