ios - Swift - 设置字典的行数

标签 ios swift dictionary

我有一个字典定义为:

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

episodesDictionary 正在从服务器获取的 JSON 文件中进行解析。

关于如何为每个部分设置行有什么想法吗?

谢谢。

最佳答案

字典不保留其键值对的顺序。因此,您无法创建一个其元素与相应标题的剧集数相对应的数组,因为它们不能保证字典将按您期望的排序顺序枚举。

相反,您需要制作一个从标题到集数的字典:

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]

Swift 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]

关于ios - Swift - 设置字典的行数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38210168/

相关文章:

ios - 尝试不使用 Google+ 按钮的 SilentAuthentication

swift - 在 Swift 中编码/解码类的重要属性的方法

c++ - map 中的两个键值可以相同吗

python - 将制表符分隔的文件放入字典(python)

ios - 有没有兼容Java和Swift的格式说明?

ios - 不兼容的 block 指针类型 SDWebImage

ios - 无法修改自定义表格 View 单元格属性

swift - 约束不断变化但布局没有更新?

ios - 如何使用 Firestore 中的对象将数据设置为数组

java - 字符 Hashmap 的替代方案(即更好的选择)