Re: [問題] Swift:類別間傳遞陣列的方法

看板MacDev作者 (阿翔)時間8年前 (2015/08/19 12:55), 8年前編輯推噓2(200)
留言2則, 2人參與, 最新討論串2/2 (看更多)
※ 引述《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://www.ptt.cc/bbs/MacDev/M.1439960128.A.A18.html ※ 編輯: johnlinvc (118.164.129.12), 08/19/2015 12:56:16

08/19 13:35, , 1F
多謝,我改用傳class進去就OK了
08/19 13:35, 1F

08/21 13:21, , 2F
inputList[0]= ture,不是xList
08/21 13:21, 2F
文章代碼(AID): #1Lr0n0eO (MacDev)
文章代碼(AID): #1Lr0n0eO (MacDev)