Swift,字符串和内存地址

Swift, Strings and Memory Addresses

关于 Swift 如何管理 String(s)

的内存地址,我有些不明白

1。引用类型

这里 fooboo 是指向 相同内存位置的 2 个指针

class Foo { }

let foo = Foo()
let boo = foo

unsafeAddressOf(foo) // "UnsafePointer(0x7FCD13719BE0)"
unsafeAddressOf(boo) // "UnsafePointer(0x7FCD13719BE0)" 

很好。

2。值类型

let word0 = "hello"
let word1 = word0

现在word0word1value types但是这里涉及到copy on write机制

[...] However, Swift only performs an actual copy behind the scenes when it is absolutely necessary to do so. Swift manages all value copying to ensure optimal performance, and you should not avoid assignment to try to preempt this optimization. https://developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/ClassesAndStructures.html#//apple_ref/doc/uid/TP40014097-CH13-XID_134

那么为什么它们有 2 个不同的内存地址?

unsafeAddressOf(word0) // "UnsafePointer(0x7FCD1342ACE0)"
unsafeAddressOf(word1) // "UnsafePointer(0x7FCD13414260)"

3。更多

另请注意,Stringstruct,即 somehow conformsAnyObject

使用 Xcode 7 GM Playground 和 Swift 2.0 进行测试。

func unsafeAddressOf(object: AnyObject) -> UnsafePointer<Void>

接受一个AnyObject参数,即class的一个实例。 它 returns 指向用于引用对象的存储的指针 通过 object.

addressOf() 不能与 struct 变量一起使用:

struct Foo { }
var f = Foo()
let a = unsafeAddressOf(f)
// error: cannot invoke 'unsafeAddressOf' with an argument list of type '(Foo)'

String 是一个 struct 但是 ,当传递给需要对象的函数时,它会自动桥接到 NSString。所以

let word0 = "hello"
let p1 = unsafeAddressOf(word0)

实际执行

let p1 = unsafeAddressOf(word0 as NSString)

你得到的不是 word0 变量的地址,而是指向 桥接 NSString 对象的内存位置。

看来你不能对这个桥接是否有任何假设 returns 相同的 NSString 对象(或更一般地说,相同的 Foundation 对象)在同一个 Swift 字符串上重复完成。在操场上,甚至

let word0 = "hello"
let p1 = unsafeAddressOf(word0)
let p2 = unsafeAddressOf(word0)
let p3 = unsafeAddressOf(word0)

returns 三个不同的地址(但编译后的地址相同 项目)。进行了相同的观察(对于数组和字典) 在 A different bridging between Array and Dictionary

Swift 3.0 Unmanaged.passUnretained(对象).toOpaque()