简体   繁体   中英

Get values of Array inside Dictionary in swift

So I have an array as the value of one of my keys in a dictionary and I want to get it to set it as the text of a UITableViewCell. How do I get it? I've been coding in Objective-C and I'm starting to learn Swift.

var content: [String: Any] = ["content": ["North America", "Europe West", "Europe Nordic & East", "Oceania", "Russia", "Turkey", "Brazil", "Latin America North", "Latin America South"], "footer": "Select the League of Legends region for this app to use."]

autoreleasepool { () -> () in
    var temp = self.content["content"]
    cell.textLabel?.text = temp[indexPath.row] as String
}

This returns me 2 errors '_??' is not convertible to 'int' '_??' is not convertible to 'int' and '<<error type>>?' is not convertible to 'int' '<<error type>>?' is not convertible to 'int'

You should declare your dictionary values as AnyObject. You should also use if let to unwrap your optionals:

let content: [String:AnyObject] = ["content": ["North America", "Europe West", "Europe Nordic & East", "Oceania", "Russia", "Turkey", "Brazil", "Latin America North", "Latin America South"], "footer": "Select the League of Legends region for this app to use."]

if let temp = content["content"] as? [String] {
     cell.textLabel!.text = temp[indexPath.row]
}

You have to convert your temp to Array for getting data.

var temp: Array = self.content["content"] as! Array
cell.textLabel?.text = temp[indexPath.row] as! String

It will solve your error.

This is because it doesn't know what's kind of type in your temp. Swift is an type safe language.

I write this in playground:

var content: [String: AnyObject] = ["content": ["North America", "Europe West", "Europe Nordic & East", "Oceania", "Russia", "Turkey", "Brazil", "Latin America North", "Latin America South"], "footer": "Select the League of Legends region for this app to use."]

var temp:NSArray = content["content"] as! NSArray

let cellString = temp[0] as! String

print(cellString)

在此输入图像描述

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