swift:修改字典中的数组 [英] swift: modifying arrays inside dictionaries

查看:24
本文介绍了swift:修改字典中的数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何轻松地向字典中的数组添加元素?它总是抱怨 could not find member 'append'could not find a Overload for '+='

How can I easily add elements to an array inside a dictionary? It's always complaining with could not find member 'append' or 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,我不会复制所有内容吗?这既不高效也不优雅.

if I just assign the array to a var, modify it and then reassign it to the dict, won't I be copying everything? that wouldn't be efficient nor elegant.

推荐答案

Swift beta 5 已添加此功能,并且您已经通过几次尝试确定了新方法.解包运算符 !? 现在将值传递给运算符或方法调用.也就是说,您可以通过以下任何一种方式添加到该数组中:

Swift beta 5 has added this functionality, and you've nailed the new method in a couple of your attempts. The unwrapping operators ! and ? now pass through the value to either operators or method calls. That is to say, you can add to that array in any of these ways:

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

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

As always, be careful about which operator you use -- force unwrapping a value that isn't in your dictionary will give you a runtime error:

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

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

Whereas using optional chaining will fail silently:

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

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

Ideally you'd be able to use the new null coalescing operator ?? to address this second case, but right now that's not working.

来自 Swift beta 5 之前的答案:

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

It's a quirk of Swift that it's not possible to do what you're trying to do. The issue is that the value of any Optional variable is in fact a constant -- even when forcibly unwrapping. If we just define an Optional array, here's what we can and can't do:

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

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

The reason you're having trouble with the dictionary is that subscripting a dictionary returns an Optional value, since there's no guarantee that the dictionary will have that key. Therefore, an array in a dictionary has the same behavior as the Optional array, above:

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 you need to change something in an array in the dictionary you'll need to get a copy of the array, change it, and reassign, like this:

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

ETA:相同的技术适用于 Swift beta 3,但常量数组不再允许更改内容.

ETA: Same technique works in Swift beta 3, though constant arrays no longer allow changes to contents.

这篇关于swift:修改字典中的数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆