Understanding Swift Array Implementation

Just out of curiosity, I wrote the 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 {
    let p = ptr(&ary)
    if(curp != p) {
        println("ptr(chgd): \(p) at index \(i)")
        curp = p



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

sometimes replaces reference variables (i.e. ary

)? Maybe I can do this by struct

assigning to myself ?

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)")
println("ptr(aftr): \(ptr(&myst)), \(myst.i)")



ptr(init): 0x00007fff57839a70, 1
ptr(news): 0x00007fff57839040, 2
ptr(aftr): 0x00007fff57839a70, 2


Does not work: (


My question is: How can I implement mine struct

as Array

? I know this is not a problem, and I believe the address doesn't make sense in Swift, but that's just for curiosity.


source to share

1 answer

Your first example doesn't show what you think. You don't get a pointer to ary

. Rather, you get a pointer to the first element ary

. You can pass an array T

with &

to a parameter expecting a pointer to T

, as described in this article on the Swift blog under "Pointers as Array Parameters".

If you change ptr


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


and then run your first example, you will see that the address ary

does not change.



All Articles