在下面的代码中,’ptr’是let声明的结构,但是它的成员变量’pointee’可以改变,为什么? let ptr = UnsafeMutablePointer Int .allocate(capacity:1) ptr.pointee = 1 UnsafeMutablePointer 是一个结构,但它声明了
let ptr = UnsafeMutablePointer< Int> .allocate(capacity:1)
ptr.pointee = 1
UnsafeMutablePointer
是一个结构,但它声明了
public struct UnsafeMutablePointer<Pointee> : Strideable, Hashable { public var pointee: Pointee { get nonmutating set } public subscript(i: Int) -> Pointee { get nonmutating set } }
这里的“非突变集”意味着设置属性不会发生变异
指针变量本身的状态.
因此,即使ptr,也可以为ptr.pointee分配一个新值
是一个常量,下标setter也是如此:
let ptr = UnsafeMutablePointer<Int>.allocate(capacity:1) ptr.pointee = 1 ptr[0] = 2