作者johnlinvc (阿翔)
看板MacDev
标题Re: [问题] Swift:类别间传递阵列的方法
时间Wed Aug 19 12:55:23 2015
※ 引述《ccshen037899 (ccshen)》之铭言:
问题点在於Swift 里的 Array 和 Dictionary 都是Struct
所以他们都是pass by value 而不是pass by reference
不过因为copy on write 最佳化的关系
他们的记忆体位址在修改前有可能相同
要做到pass by reference 的话可以用下面几种方法
1.用NSMutableArray
2.用一个wrapper class 把 array 包起来
3.把xList 当成 f 的 inout parameter
范例playground
https://gist.github.com/johnlinvc/082540939ef8acc8182a
: 各位好:
: 我目前建立了两个class,想要在classB内更改classA.xList的值
: 执行结果却不如预期;我试着用classA内的函式搭配inout是可以的
: 请问我的写法是哪里有误吗?
: class A {
: var xList=[Bool](count:21 repeatedValue:false)
: func X {
: var b=B(xList:&xList) //把阵列传入
: b.f() //在这里更改阵列内的值
: }
: class B {
: var xList:[Bool]
: init(inout inputList:[Bool]) {
: self.xList=inputList //接收阵列
: }
: func f() {
: xList[0]=true //想更改阵列的值,但是A.xList没有变更
: }
: }
: func setArray(inout inputList) {
: inputList[0]=true //classA内的函式,可以正确更改A.xList
: }
: }
--
※ 发信站: 批踢踢实业坊(ptt.cc), 来自: 118.164.129.12
※ 文章网址: https://webptt.com/cn.aspx?n=bbs/MacDev/M.1439960128.A.A18.html
※ 编辑: johnlinvc (118.164.129.12), 08/19/2015 12:56:16
1F:推 ccshen037899: 多谢,我改用传class进去就OK了 08/19 13:35
2F:推 truthmanman: inputList[0]= ture,不是xList 08/21 13:21