ios - Swift - 带有元组数组的字典

标签 ios swift

我正在尝试创建一个列表来保存包含部分的表格 View 的数据。

我想这样使用它:

cell.NameLabel.text = list[indexPath.section][indexPath.row].name

<罢工> 已编辑

我试图让问题变得简单,因为英语不是我的主要语言。 让我尝试问正确的问题:

我想创建一个包含元组数组的字典 类似这样的事情:

var myDict = Dictionary<Array<(code: String, type:  String)>>()

我想这样访问:

myDict["blue"][0].type

最佳答案

示例中的 myDict 声明是错误的,因为 Dictionary 需要键的类型和值的类型。您应该将其声明为:

var myDic = Dictionary<String, Array<(code: String, type:  String)>>()

然后,您就可以(几乎)按照您想要的方式使用它:

myDic["one"] = [(code: "a", type: "b")]
myDic["two"] = [(code: "c", type: "d"), (code: "e", type: "f")]

let t = myDic["two"]![0].type
...

请注意 myDic["two"] 之后的 !。那是因为通过按键访问 Dictionary 会返回一个 Optional,您需要先将其解开。

实际上,这段代码会更好:

if let item: Array<(code: String, type:  String)> = myDic["two"] {
    let t = item[0].type
    ...
}

关于ios - Swift - 带有元组数组的字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29831036/

相关文章:

ios - 给mkmap添加注解,想去掉部分注解却不会去掉

ios - 我可以在 for 循环中将键值对添加到 NSarray 或字典吗?

ios - 为什么以编程方式创建的(底部)工具栏按钮标题不显示?

ios - SFSpeechRecognizer init 不接受区域设置

Swift Hashing 算法使用位移来避免冲突

swift - 在应用程序启动时显示 UIAlertView

iOS Swift Realm 同步问题

ios - 按屏幕大小缩放文本标签

ios - 在 Swift 中以编程方式突出显示 UITableViewCell

swift - 如何将符合 Codable 协议(protocol)的枚举保存到 UserDefaults?