arrays - swift:修改字典中的数组

标签 arrays dictionary syntax swift

如何轻松地将元素添加到字典中的数组中? 它总是提示 could not find member 'append'could not find an overload for '+='

var dict = Dictionary<String, Array<Int>>()
dict["key"] = [1, 2, 3]

// all of these fail
dict["key"] += 4
dict["key"].append(4) // xcode suggests dict["key"].?.append(4) which also fails
dict["key"]!.append(4)
dict["key"]?.append(4)

// however, I can do this:
var arr = dict["key"]!
arr.append(4) // this alone doesn't affect dict because it's a value type (and was copied)
dict["key"] = arr

如果我只是将数组分配给一个 var,修改它然后将它重新分配给 dict,我不会复制所有内容吗?那既不高效也不优雅。

最佳答案

Swift beta 5 已经添加了这个功能,你已经在几次尝试中找到了这个新方法。展开运算符 !? 现在将值传递给运算符或方法调用。也就是说,您可以通过以下任何一种方式添加到该数组:

dict["key"]! += [4]
dict["key"]!.append(4)
dict["key"]?.append(4)

与往常一样,请注意您使用的运算符——强制解包一个不在您的字典中的值会给您带来运行时错误:

dict["no-key"]! += [5]        // CRASH!

而使用可选链接将无提示地失败:

dict["no-key"]?.append(5)     // Did it work? Swift won't tell you...

理想情况下,您可以使用新的空合并运算符 ?? 来解决第二种情况,但现在它不起作用。


pre-Swift beta 5 的回答:

这是 Swift 的一个怪癖,它不可能做你想做的事。问题是任何 Optional 变量的 value 实际上是一个常量——即使在强制解包时也是如此。如果我们只定义一个 Optional 数组,下面是我们能做什么和不能做什么:

var arr: Array<Int>? = [1, 2, 3]
arr[0] = 5
// doesn't work: you can't subscript an optional variable
arr![0] = 5
// doesn't work: constant arrays don't allow changing contents
arr += 4
// doesn't work: you can't append to an optional variable
arr! += 4
arr!.append(4)
// these don't work: constant arrays can't have their length changed

您在使用字典时遇到问题的原因是下标字典会返回一个可选值,因为不能保证字典将具有该键。因此,字典中的数组与上面的可选数组具有相同的行为:

var dict = Dictionary<String, Array<Int>>()
dict["key"] = [1, 2, 3]
dict["key"][0] = 5         // doesn't work
dict["key"]![0] = 5        // doesn't work
dict["key"] += 4           // uh uh
dict["key"]! += 4          // still no
dict["key"]!.append(4)     // nope

如果您需要更改字典中数组中的某些内容,您需要获取该数组的副本、更改它并重新分配,如下所示:

if var arr = dict["key"] {
    arr.append(4)
    dict["key"] = arr
}

预计到达时间:相同的技术适用于 Swift beta 3,但常量数组不再允许更改内容。

关于arrays - swift:修改字典中的数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24534229/

相关文章:

python - 将函数映射到 numpy 数组,改变参数

css 不工作背景悬停事件 - 不是语法问题

c - 堆栈数组变量不一致 C

c++ - 在非常小的数组中找到最小值

c# - 名字和姓氏的数组连接

python - 在 python 中创建一个通用字典,从多对列表中获取键值对

c# - 泛化构造函数以在 C# 中对数组进行操作

带有 setter 的 C++ 类,它接受一个输入指针,稍后将值返回给该指针

rust - Rust 中的 "()"类型是什么?

swift - NotificationCenter 将 swift 3 迁移到 swift 4.2 的问题