ios - Swift:创建字典值数组

标签 ios arrays uitableview dictionary swift

我是 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/

相关文章:

ios - statusCode 应该是 200,但是是 415

ios - 同步取数据 NSOperationQueue 或 NSURLSession

IOS UIButton 不响应触摸,需要多次按下,UIScreenEdge 手势干扰?

c - 用C读取文件并将数据存储在数组中

在 C 中通过引用传递数组时崩溃

ios - 如何使用户无需在 URL 前键入 "http://"?

java - 为什么在Java中使用[]创建数组而不是创建数组对象?

ios - UITableView - 如何在拖放期间更改单元格的背景颜色?

ios - UITableView 在 ios 中使用自定义表格单元格滚动不流畅

ios - 分组部分 UITableView swift IOS 中的重复值