您对什么是类型和什么是值感到困惑。您已经定义了四种类型,但您需要的是两种类型,以及这些类型的一些实例(值)。
以下是您需要的类型:
struct Chapter {
let categories: [Category]
}
struct Category {
let name: String
let content: String
}
这里是一个数组值,包含一个Chapter类型的值,其中包含三个Category类型的值:
let chapters: [Chapter] = [
Chapter(categories: [
Category(name: "Data Structures", content: "structs, classes, enums, tuples, etc."),
Category(name: "Algorithms", content: "sorting, searching, calculating, etc."),
Category(name: "Programs", content: "Flappy Bird, Microsoft Word, etc."),
])
]
您可以像这样定义表格视图数据源:
class MyDataSource: NSObject, UITableViewDataSource {
let chapters: [Chapter] = [
Chapter(categories: [
Category(name: "Data Structures", content: "structs, classes, enums, tuples, etc."),
Category(name: "Algorithms", content: "sorting, searching, calculating, etc."),
Category(name: "Programs", content: "Flappy Bird, Microsoft Word, etc."),
])
]
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return chapters.count
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return chapters[section].categories.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("CategoryCell", forIndexPath: indexPath) as! CategoryCell
let category = chapters[indexPath.section].categories[indexPath.row]
cell.category = category
return cell
}
}
如果segue连接到故事板中的单元格之外,那么单元格本身就是发送者,所以你可以这样处理:
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "CategoryDetail" {
let cell = sender as! CategoryCell
let categoryDetailViewController = segue.destinationViewController as! CategoryDetailViewController
categoryDetailViewController.category = cell.category
}
}