Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Understanding Array implementation of Swift

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.

like image 564
rintaro Avatar asked Feb 04 '26 07:02

rintaro


1 Answers

Your first example doesn't show what you think. You are not getting a pointer to ary. Rather, you are getting a pointer to the first element of ary. You can pass an array of T with & to a parameter expecting pointer to T, as described in this Swift blog article, under "Pointers as Array Parameters".

If you change ptr to

func ptr(x:UnsafePointer<[Int]>) -> UnsafePointer<Void> {
  return UnsafePointer<Void>(x)
}

and then run your first example, you will see that the address of ary does not change.

like image 98
newacct Avatar answered Feb 06 '26 20:02

newacct



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!