了解Swift的数组实现

时间:2014-09-24 03:33:11

标签: ios macos memory-management swift

出于好奇,我在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
    }
}

输出:

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

嗯,我想,Array偶尔会替换引用变量(即ary)? 也许我可以通过assigning to self struct使用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)") 来完成此操作?

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

输出:

struct

不起作用:(

-

我的问题是如何实施我的Array {{1}}?我知道这不是问题,我相信Swift中的地址毫无意义,但这只是为了好奇。

1 个答案:

答案 0 :(得分:3)

你的第一个例子没有显示你的想法。你没有得到ary的指针。相反,您将获得指向ary的第一个元素的指针。您可以将带有T的{​​{1}}数组传递给期望指向&的参数,如this Swift blog article中所述,&#34;指针作为数组参数&#34;

如果您将T更改为

ptr

然后运行第一个示例,您会看到func ptr(x:UnsafePointer<[Int]>) -> UnsafePointer<Void> { return UnsafePointer<Void>(x) } 的地址没有变化。