我是 Swift 的新手。我有一个 TableView Controller ,我在其中声明了以下内容:
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 数组和字典实际上是不可变的。我只是想知道是否有人可以证实这一点。预先感谢您的回复。
最佳答案
你只是不需要values.array
:
var chapterTitles = partsOfNovel[sectionTitle]!
只要字典本身是可变的,字典中的数组就可以改变,但您需要通过解包运算符进行赋值:
if partsOfNovel[sectionTitle] != nil {
partsOfNovel[sectionTitle]!.append("foo")
}
关于ios - Swift:创建字典值数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26823286/