简体   繁体   English

Swift:创建字典值数组

[英]Swift: Create Array of Dictionary Values

I am very new to Swift. 我对Swift很新。 I have a table view controller in which I have declared the following: 我有一个表视图控制器,我在其中声明了以下内容:

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

In my viewDidLoad function, I have: 在我的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)

In my cellForRowAtIndexPath function, I have: 在我的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]

I am trying to create an array, secTitles, consisting of the values from the parts dictionary that correspond to the keys, sectionTitle. 我正在尝试创建一个数组secTitles,它由与字符对应的parts字典中的值sectionTitle组成。 However, I received this error message: 但是,我收到此错误消息:

'String' is not convertible to 'Int' 'String'不能转换为'Int'

I was able to do it in Objective-C: 我能够在Objective-C中做到这一点:

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

Also, I would like to know if I will be able to add/remove the the values in the arrays and dictionaries later on. 此外,我想知道我以后是否能够添加/删除数组和字典中的值。 In other words, are they mutable? 换句话说,它们是否可变? I've read a few articles that say Swift arrays and dictionaries aren't actually mutable. 我读过一些文章,说Swift数组和字典实际上并不可变。 I just wanted to know if anyone could confirm that. 我只是想知道是否有人可以确认。 Thank you in advance for your responses. 提前感谢您的回复。

You just don't need the values.array : 你只是不需要values.array

var chapterTitles = partsOfNovel[sectionTitle]!

Arrays inside dictionaries can be mutated as long as the dictionary itself is mutable, but you'll need to assign through an unwrapping operator: 只要字典本身是可变的,字典中的数组就可以变异,但是你需要通过一个解包运算符来分配:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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