luke
luke

Reputation: 2773

Looping through dictionary to find value

Usually I just step into the dictionary and find the value once inside. In this case, I need to step in, loop through to find a value then step back out again then find a different value. Example:

address_components": [
{
    "long_name": "E3 2AA",
    "short_name": "E3 2AA",
    "types": [
        "postal_code"
    ]
},
{
    "long_name": "London",
    "short_name": "London",
    "types": [
        "postal_town"
    ]
}
]

This is what googles api dictionary looks like and I need to fetch the long_name of the postal_town.

Upvotes: 0

Views: 47

Answers (4)

Mo Abdul-Hameed
Mo Abdul-Hameed

Reputation: 6110

This should do it for you:

let result = addressComponents.filter({ return ($0["types"] as! [String]).contains("postal_town") }).map({ $0["long_name"] })

Upvotes: 2

vadian
vadian

Reputation: 285079

You can use the first(where: function passing a closure to filter for the type, this avoids a loop:

if let addressComponents = json["address_components"] as? [[String:Any]],
    let postalTownComponent = addressComponents.first(where: { ($0["types"] as! [String]).contains("postal_town")  }) {
    print(postalTownComponent["long_name"])
}

Upvotes: 2

Lawliet
Lawliet

Reputation: 3499

Should it just that simple, or I misunderstand your question? An example:

let dict = [ "long_name": "E3 2AA", "short_name": "E3 2AA"]
for (key, value) in dict {
    print("your key: \(key) and value: \(value)")
}

Upvotes: 0

FrenchMajesty
FrenchMajesty

Reputation: 1139

address_components is an array so you can just loop over it and check the value of your key. Maybe something like:

var names = []

for entry in addressComponent {
    if addressComponent["types"][0] == "postal_town" {
        names.append(addressComponent["long_name"])
    }
}

Upvotes: 0

Related Questions