user4708651
user4708651

Reputation: 55

How to easily read AnyObject stored in dictionaries?

I have a dictionary that stores strings and integers. This dictionary's type is [String:AnyObject].

var person: [String:AnyObject] = ["occupation": "teacher", "age": 1]

I read this dictionary by this way:

occupationLabel.text = person["occupation"] as! String
let newAge = person["age"] as! Int + 1

It's inconvenient. How can I use this dictionary by the following way?

occupationLabel.text = person["occupation"]
let newAge = person["age"] + 1

Thank you.

Upvotes: 0

Views: 29

Answers (1)

matt
matt

Reputation: 535121

You can't. You threw away static typing of the dictionary values when you made this a [String:AnyObject]. What you are doing, casting each value to what you know it to be, is correct.

The real solution, of course, is to have a Person type with occupation and age properties!

struct Person {
    var occupation:String
    var age:Int
}

Now each property has an inherent type and you don't need to cast.

Upvotes: 1

Related Questions