我将字典定义为:
var episodesDictionary = [String: [Episode]]()
字典中的每个项目都可以有一定数量的剧集,例如:
title1: episode1, episode2, episode3
title2: episode1, episode2
title3: episode1, episode2, episode3, episode4
我想要的是设置一张桌子。所以在numberofSectionsInTableView中我返回
episodesDictionary.count
问题是我不知道如何获得每个部分的行数。我尝试了以下方法:
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
var episodes = [Int]()
for (key, value) in episodesDictionary {
var shows = [String]()
shows.append(key)
episodes.append(value.count)
}
return episodes[section]
}
但我总是得到0
正在从从服务器获取的JSON文件中解析episodesDictionary。
关于如何设置每个部分的行的任何想法?
感谢。
答案 0 :(得分:2)
字典不会保留其键值对的排序。因此,您不能创建一个数组,其元素与相应标题的剧集数相对应,因为它们并不能保证字典将按照您所期望的排序顺序进行枚举。
相反,你需要制作一个从标题到剧集数量的字典:
let episodes = [
"title1" : ["episode1", "episode2", "episode3"],
"title2" : ["episode1", "episode2"],
"title3" : ["episode1", "episode2", "episode3", "episode4"],
]
let episodeCounts = episodes.mapValues { $0.count }
print(episodeCounts) //prints ["title1": 3, "title2": 2, "title3": 4]
没有mapValues
,所以你必须自己写一下:
let dict = [
"title1" : ["episode1", "episode2", "episode3"],
"title2" : ["episode1", "episode2"],
"title3" : ["episode1", "episode2", "episode3", "episode4"],
]
var episodeCounts = [String : Int]()
for (title, episodes) in dict {
episodeCounts[title] = episodes.count
}
print(episodeCounts) //prints ["title1": 3, "title2": 2, "title3": 4]
答案 1 :(得分:1)
似乎您使用的词典可能不是最佳选择。尝试使用元组,例如:
let elements: [(title: String, episodes: [String])] = [
("title1", ["episode1", "episode2", "episode3"]),
("title2", ["episode1", "episode2"]),
("title3", ["episode1", "episode2", "episode3", "episode4"]),
]
可以让你像这样处理numberOfRowsInSection:
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return elements[section].episodes.count
}