Swift,字符串和内存地址 [英] Swift, Strings and Memory Addresses
问题描述
对于Swift如何管理String(s)
There is something I am not understanding about how Swift manages memory address of String(s)
此处foo
和boo
是指向相同存储位置的2个指针.
Here foo
and boo
are 2 pointers to the same memory location.
class Foo { }
let foo = Foo()
let boo = foo
unsafeAddressOf(foo) // "UnsafePointer(0x7FCD13719BE0)"
unsafeAddressOf(boo) // "UnsafePointer(0x7FCD13719BE0)"
好.
let word0 = "hello"
let word1 = word0
现在word0
和word1
是value types
,但是这里涉及到copy on write
机制.
Now word0
and word1
are value types
but here the copy on write
mechanism is involved.
[...]但是,Swift仅在绝对必要时才在幕后执行实际复制. Swift会管理所有值复制以确保最佳性能,因此您不应避免分配以尝试抢占该优化. 那么为什么它们有2个不同的内存地址?
So why do they have 2 different memory addresses?
unsafeAddressOf(word0) // "UnsafePointer(0x7FCD1342ACE0)" unsafeAddressOf(word1) // "UnsafePointer(0x7FCD13414260)"
3.更多
还请注意,
String
是某种程度上符合的struct
a>到AnyObject
.
3. More
Also please note that
String
is astruct
that somehow conforms toAnyObject
.通过Xcode 7 GM Playground和Swift 2.0进行了测试.
Tested with Xcode 7 GM Playground and Swift 2.0.
推荐答案
func unsafeAddressOf(object: AnyObject) -> UnsafePointer<Void>
带有
AnyObject
参数,即 class 的实例. 它将指针返回到用于所引用对象的存储 通过object
.takes an
AnyObject
parameter, i.e. an instance of a class. It returns the pointer to the storage used for the object referenced byobject
.
addressOf()
不能与 struct 变量一起使用:
addressOf()
cannot be used with struct variables:
struct Foo { } var f = Foo() let a = unsafeAddressOf(f) // error: cannot invoke 'unsafeAddressOf' with an argument list of type '(Foo)'
String
是struct
,但是 ,当传递给需要对象的函数时,它会自动桥接到NSString
.所以
String
is astruct
, however, it is automatically bridged toNSString
when passed to a function expecting an object. So
let word0 = "hello" let p1 = unsafeAddressOf(word0)
实际执行
let p1 = unsafeAddressOf(word0 as NSString)
您不是获得
word0
变量的地址,而是指向该变量的指针. 桥接的NSString
对象的内存位置.You get not the address of the
word0
variable, but the pointer to the memory location of the bridgedNSString
object.您似乎无法对这种桥接是否做出任何假设 返回相同的
NSString
对象(或更常见的是,相同的 基础对象)在同一Swift字符串上重复执行.在操场上,甚至It seems that you cannot make any assumptions on whether this bridging returns the identical
NSString
object (or more generally, the same Foundation object) when done repeatedly on the same Swift string. In a Playground, even
let word0 = "hello" let p1 = unsafeAddressOf(word0) let p2 = unsafeAddressOf(word0) let p3 = unsafeAddressOf(word0)
返回三个不同的地址(但在编译后返回相同的地址 项目).进行了相同的观察(对于数组和字典) 在数组与字典之间的不同桥接中.
returns three different addresses (but the same addresses in a compiled project). The same observation (for arrays and dictionaries) was made in A different bridging between Array and Dictionary.
这篇关于Swift,字符串和内存地址的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!