简体   繁体   English

在字典内的数组中附加int

[英]Append int in array inside dictionary

I use this line to append indexPath.row in array in dictionary. 我用这一行将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)")

}

And this line to check. 和这行检查。

print("downloadQ:\(downloadQ)")

But my array not append indexPath.row in console I get this downloadQ:[:] 但是我的数组没有在控制台中追加indexPath.row我得到了这个downloadQ:[:] indexPath.row downloadQ:[:]

How to fix it? 如何解决?

eg 例如

downloadQ[1] = [1,2]
downloadQ[2] = [1,2]

var arr = downloadQ[2]
arr?.append(3)
downloadQ[2] = arr
print(downloadQ)

What you doing is just appending your new item into array, but you have to replace that array in your dictionary. 您所做的只是将新项追加到数组中,但是您必须在字典中替换该数组。 so, after appending your array item assign your array in dictionary. 因此,在追加数组项之后,在字典中分配数组。

downloadQ[2] = arr
print(downloadQ)

That's it. 而已。

When you create your dictionary it is initially empty, that is, it doesn't contain any arrays for any keys. 创建字典时,字典最初是空的,也就是说,它不包含任何键的任何数组。

When you say downloadQ[id]?.append(indexPath.row) , downloadQ[id] is nil as you have never stored an array for key id . 当您说downloadQ[id]?.append(indexPath.row)downloadQ[id]nil因为您从未存储过用于键id的数组。 The append is then ignored since you have conditionally unwrapped downloadQ[id] . 由于您已经有条件地解包了downloadQ[id]因此将忽略该追加。

You need to handle the case where there is no array for the key. 您需要处理键没有数组的情况。 The nil coalescing operator is a nice way to do this. nil合并运算符是执行此操作的好方法。 Something like 就像是

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM