OGeek|极客世界-中国程序员成长平台

标题: ios - 在字典内的数组中追加 int [打印本页]

作者: 菜鸟教程小白    时间: 2022-12-11 19:54
标题: ios - 在字典内的数组中追加 int

我使用这一行将 indexPath.row 附加到字典中的数组中。

var downloadQ = [Int: [Int]]()
var id = 1

override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

    downloadQ[id]?.append(indexPath.row)
    print("downloadQ:\(downloadQ)")

}

还有这条线要检查。

print("downloadQ:\(downloadQ)")

但我的数组没有在控制台中附加 indexPath.row 我得到这个 downloadQ:[:]

如何解决?



Best Answer-推荐答案


当您创建字典时,它最初是空的,也就是说,它不包含任何键的任何数组。

当你说 downloadQ[id]?.append(indexPath.row) 时,downloadQ[id]nil 你从来没有为键 id 存储了一个数组。然后忽略附加,因为您有条件地解包 downloadQ[id].

您需要处理键没有数组的情况。 nil 合并运算符是一种很好的方法。类似的东西

var theArray = downloadQ[id] ?? [Int]()
theArray.append(indexPath.row)
downloadQ[id] = theArray

关于ios - 在字典内的数组中追加 int,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49462035/






欢迎光临 OGeek|极客世界-中国程序员成长平台 (http://ogeek.cn/) Powered by Discuz! X3.4