I have the following playground code:
import UIKit
import XCPlayground
class A {
var arr : [UIImage] = []
func addItem(inout localArr: [UIImage]) {
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (Int64)(2 * NSEC_PER_SEC)), dispatch_get_main_queue()) { () -> Void in
localArr.append(UIImage())
print("from inside function localArr: \(localArr)")
print("form inside function: \(self.arr)")
}
}
}
let a = A()
a.addItem(&a.arr)
print("instant print :\(a.arr)")
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (Int64)(3 * NSEC_PER_SEC)), dispatch_get_main_queue()) { () -> Void in
print("print after delay: \(a.arr)")
}
XCPlaygroundPage.currentPage.needsIndefiniteExecution = true
The output is:
instant print :[]
from inside function localArr: [<UIImage: 0x7f99e8706f10>, {0, 0}]
form inside function: []
print after delay: []
My question is, why is localArr
not the same as self.arr
inside the addItem
and not the same as a.arr
outside? My expectation was that when I pass the parameter as inout
I should be able to operate on the actual object, not the copy, but clearly this is not what happens.
Edit: So thanks to dfri answer I know why this doesn't work. The inout
is really call-by-copy-restore, check another answer here. Now, any suggestion on how to actually make the closure to capture the reference to the original object? Or perhaps I should use other technique to achieve what I want?