andre g andre g - 5 months ago 11
Swift Question

swift: passing by reference

Coming from JS, and trying to pass [JSON] by reference in swift, which is not possible, so I'm trying to wrap it in the object, and made a simple example using a primitive, which still not working, how can i wrap member a, so that changes in referenced object a affect b ? Thanks

class ExampleA {
var a = 0
init(a: Int) {
self.a = a
}
}
class ExampleB {
var a = 0
init(a: Int) {
self.a = a
}
func process(inout p: ExampleA) {
self.a = p.a
print(p.a)
}
}

var a = ExampleA(a: 15)
var b = ExampleB(a: 10)

b.process(&a)

print(b.a) // "15\n"
a.a = 25 // this does nothing to b????
print(b.a) // "15\n"

Answer

Your example fails because a is an Int, which is a value type.

When you do the assignment self.a = p.a, you're making a copy of the Int.

To achieve the reference semantics you want, you have to hold reference the ExampleA that's storing the value type. I think you got confused because of your variable naming.