user7684436
user7684436

Reputation: 717

Swift 3 - Get value from array of dictionaries

Trying to get the value and the key of a dictionary that's stored in an array to populate two UILabels.

My array looks as follows:

var fromLocations = [["marco" : "polo"],["jekyll" : "hide"],["freddy" : "jason"]]

I'm getting the index by a collection view's indexPath. Currently trying the following:

cell.locationName.text = fromLocations[indexPath.item].values[1]

I've tried a bunch of other ways but I can't nail it.

Upvotes: 2

Views: 5147

Answers (1)

kailoon
kailoon

Reputation: 2069

Is this what you are trying to do?

var fromLocations = [["marco" : "polo1"],["marco" : "polo2"],["marco" : "polo3"]]
let marco = fromLocations[0]["marco"]
print("marco = \(marco)")

This prints "polo1". Basically you are accessing the first item of the array which is a dictionary. You then access that dictionary the way you would normally access a dictionary.

So a break down would be:

let fromLocations = [["marco" : "polo"],["marco" : "polo"],["marco" : "polo"]]
let theDictionary = fromLocations[0]
let value = theDictionary["marco"]

To just get the values as an array with using the key (which is strange), turn the values into an array.

var fromLocations = [["marco" : "polo1"],["marco" : "polo2"],["marco" : "polo3"]]
let marco = Array(fromLocations[0].values)[0]
print("marco = \(marco)")

This will print "polo1"

Upvotes: 3

Related Questions