【问题标题】:Swift: Create Array of Dictionary ValuesSwift:创建字典值数组
【发布时间】:2015-01-05 13:06:06
【问题描述】:

我对 Swift 很陌生。我有一个表视图控制器,我在其中声明了以下内容:

var parts = [String:[String]]() //Key: String, Value: Array of Strings
var partsSectionTitles = [String]()

在我的 viewDidLoad 函数中,我有:

parts = [
        "Part 1" : ["1", "2", "3"],
        "Part 2" : ["1", "2"],
        "Part 3" : ["1"]
    ]

//Create an array of the keys in the parts dictionary
partsSectionTitles = [String](parts.keys)

在我的 cellForRowAtIndexPath 函数中,我有:

let cell = tableView.dequeueReusableCellWithIdentifier("TableCell", forIndexPath: indexPath) as UITableViewCell

var sectionTitle: String = partsSectionTitles[indexPath.section]
var secTitles = parts.values.array[sectionTitle]

cell.textLabel.text = secTitles[indexPath.row]

我正在尝试创建一个数组 secTitles,它由对应于键 sectionTitle 的部件字典中的值组成。但是,我收到此错误消息:

'String' 不能转换为 'Int'

我能够在 Objective-C 中做到这一点:

NSString *sectionTitle = [partsSectionTitles objectAtIndex:indexPath.section];
NSArray *secTitles = [parts objectForKey:sectionTitle];

另外,我想知道我以后是否能够添加/删除数组和字典中的值。换句话说,它们是可变的吗?我读过一些文章说 Swift 数组和字典实际上不是可变的。我只是想知道是否有人可以证实这一点。提前感谢您的回复。

【问题讨论】:

    标签: ios arrays uitableview dictionary swift


    【解决方案1】:

    你只是不需要values.array

    var chapterTitles = partsOfNovel[sectionTitle]!
    

    只要字典本身是可变的,字典中的数组就可以被改变,但是你需要通过一个展开操作符来赋值:

    if partsOfNovel[sectionTitle] != nil {
        partsOfNovel[sectionTitle]!.append("foo")
    }
    

    【讨论】:

    • 结果是可选的 - 如果您确定密钥有效,您可以使用 ! 强制解包,或者如果您不是,则使用可选绑定或 nil 合并运算符来解包. (答案现在显示强制展开。)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-02-02
    • 1970-01-01
    • 2018-01-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-06
    相关资源
    最近更新 更多