user4708651 user4708651 - 5 months ago 17
Swift Question

How to easily read AnyObject stored in dictionaries?

I have a dictionary that stores strings and integers. This dictionary's type is


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.


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.