斯威夫特对象引用数组? [英] Swift Object reference to array?
问题描述
我可能错过了关于SWIFT的重要信息。我有一张地图包含键/快捷阵列对。我改变了阵列和地图中阵没有改变。有人能解释一下这是怎么回事?谢谢!
VAR地图= [字符串:[字符串]()
VAR名单= [字符串]()
图[名单] =清单//输出:[清单:[]的\\ n
打印(图)list.append(测试)
打印(列表)//输出:[测试] \\ n
打印(图)//输出:[清单:[]的\\ n
当你已经被告知,这些(字典和数组)是的值类型的。所以一般你要寻找的方法是简单地采取从数组的字典,修改它,并把它再次插入:
VAR地图= [字符串:[字符串]()
图[清单] = [字符串]()VAR列表=图[名单]!
list.append(测试)
图[名单] =名单
但是,还有另一种方法:你可以得到一种指针到字典里面的阵列,但是只有当你使用INOUT 参数与的功能。例如:
VAR地图= [字符串:[字符串]()
图[清单] = [字符串]()FUNC追加(S:字符串,INOUT到ARR:[字符串]){
ARR + = [S]
}
追加(测试,到:及(图[名单))
这其实只是同一事物的符号,但如果你打算做了很多这方面你可能preFER它。
I probably missed an important information about swift. I have a map contains a key / swift array pair. I changed the array and the array inside the map was not changed. Could someone explain what is going on? Thanks!
var map = [String:[String]]()
var list = [String]()
map["list"] = list //output: "["list": []]\n"
print(map)
list.append("test")
print(list) //output: "["test"]\n"
print(map) //output: "["list": []]\n"
As you've been told, these (dictionaries and arrays) are value types. So in general the technique you're looking for is simply to take the array out of the dictionary, modify it, and put it back in again:
var map = [String:[String]]()
map["list"] = [String]()
var list = map["list"]!
list.append("test")
map["list"] = list
However, there's another way: you can get a sort of pointer to the array inside the dictionary, but only if you use a function with an inout
parameter. For example:
var map = [String:[String]]()
map["list"] = [String]()
func append(s : String, inout to arr : [String]) {
arr += [s]
}
append("test", to: &(map["list"]!))
That's actually just a notation for the same thing, but if you're going to do a lot of this you might prefer it.
这篇关于斯威夫特对象引用数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!