简体   繁体   中英

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.

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"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM