leisdorf
leisdorf

Reputation: 51

Retrieving data from dictionary Swift

I am trying to retrieve data from a dictionary and assign the value to "city". I would like to use information[1]["City"], but that generates an error, as well. Also, not sure if I need to unwrap an optional here.

let locals = ["Jerry":["City": "Seattle", "Preference": "Adventurer"],"Emily":["City": "Boston", "Preference": "History Buff"]              


func matchTravellerWithLocal(location: String, type: String) -> String {
    var message = " "
    let locals = LocalsInformation().locals
    for (name, information) in locals{
        let city = information["City"]!
        print(city)
        let preference = information["Preference"]
        if city == location{
            message = "Meet your local: \(name), a local of \(city)"
        }else{
            message = "Apologies, there aren't in \(city) on     LocalRetreat. Try again soon!"
            break
        }
        if preference == type{
            message += "who is also a \(preference)"
        }
    }
    return message
}

Upvotes: 2

Views: 78

Answers (1)

Ramis
Ramis

Reputation: 16519

Your locals should be defined like this:

let locals: [[String: Dictionary<String, String>]] = [["Jerry":["City": "Seattle", "Preference": "Adventurer"]],["Emily":["City": "Boston", "Preference": "History Buff"]]]

Then you can access it like that:

let jerry = locals[0]["Jerry"]

Upvotes: 2

Related Questions