1

I have a Contact object which can have and array of Address objects.

class Contact {
    var firstName: String = ""
    var lastName: String = ""
    var middleName: String = ""
    var id: Int = -1
    var addresses: Array<Address> = []

How would I initialize each Address object while fetching it from json dictionary?

init(json: Dictionary<String, AnyObject>) {

        if let line1 = json["streetLine"] as? String {
            self.streetLine1 = line1
        }
        if let city = json["city"] as? String {
            self.city = city
        }
        if let state = json["state"] as? String {
            self.state = state
        }
        if let zip = json["zip"] as? Int {
            self.zip = zip
        }

Tried doing like this:

if let addressMap = json["addresses"] as? Array<Dictionary<String, AnyObject?>> {
            for address as? Address in addressMap {
                addresses.append(address)
            }
        }

2 Answers 2

6

Try this:

if let dictionaryArray = json["addresses"] as? Array<Dictionary<String, Anyobject?>> 
    for address in dictionaryArray {
        var address = Address(json: address)
        addresses.append(address)
    }
}

So you get your list of Dictionarys from your json, loop through them and then use your init function to inject the data into your class.

Sign up to request clarification or add additional context in comments.

Comments

0

Try this

addresses = (json["addresses"] as? Array<Dictionary<String, AnyObject?>>)?.map{Address(json: $0)}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.