Just out of curiosity, I wrote following code in Swift:
func ptr(x:UnsafePointer<Void>) -> UnsafePointer<Void> {
return x
}
var ary = [Int]()
var curp = ptr(&ary)
println("ptr(init): \(curp)")
for i in 0 ... 100000 {
ary.append(i)
let p = ptr(&ary)
if(curp != p) {
println("ptr(chgd): \(p) at index \(i)")
curp = p
}
}
output:
ptr(init): 0x00007fa233449b60
ptr(chgd): 0x00007fa23344db50 at index 0
ptr(chgd): 0x00007fa23344e4b0 at index 2
ptr(chgd): 0x00007fa23344e600 at index 4
ptr(chgd): 0x00007fa23344f0a0 at index 8
ptr(chgd): 0x00007fa23344eeb0 at index 16
ptr(chgd): 0x00007fa23344f1e0 at index 32
ptr(chgd): 0x00007fa233840420 at index 64
ptr(chgd): 0x00007fa233840a20 at index 188
ptr(chgd): 0x00007fa233841620 at index 380
ptr(chgd): 0x00007fa233842e20 at index 764
ptr(chgd): 0x00007fa23403ca20 at index 1532
ptr(chgd): 0x00007fa233845e20 at index 3068
ptr(chgd): 0x00007fa23480f820 at index 6140
ptr(chgd): 0x00000001140b7020 at index 12284
ptr(chgd): 0x000000011731b020 at index 33276
ptr(chgd): 0x000000011739d020 at index 66556
Hmm, I thought, Array occasionally replaces the referencing variables(i.e. ary)?
Maybe I can do this with my struct by assigning to self?
struct MyStruct {
var i = 0
mutating func mutate(i:Int) {
var newself = MyStruct(i: i)
println("ptr(news): \(ptr(&newself)), \(newself.i)")
self = newself
}
}
var myst = MyStruct(i: 1)
println("ptr(init): \(ptr(&myst)), \(myst.i)")
myst.mutate(2)
println("ptr(aftr): \(ptr(&myst)), \(myst.i)")
output:
ptr(init): 0x00007fff57839a70, 1
ptr(news): 0x00007fff57839040, 2
ptr(aftr): 0x00007fff57839a70, 2
Not works :(
--
My question is How can I implement my struct like Array? I know this is not a problem, and I believe the address is meaningless in Swift, but it's just for curiosity.