UnsafeMutablePointer
struct UnsafeMutablePointer<Pointee>
用于访问和操作特定类型数据的指针。
你使用 UnsafeMutablePointer 类型的实例来访问内存中特定类型的数据。指针可以访问的数据类型是指针的 Pointee 类型。UnsafeMutablePointer 不提供自动内存管理或对齐保证。你负责通过不安全的指针处理你使用的任何内存的生命周期,以避免泄漏或未定义的行为。
你手动管理的内存可以是无类型的,也可以绑定到特定类型。你使用 UnsafeMutablePointer 类型来访问和管理已绑定到特定类型的内存。 ( 来源 )
import Foundation
let arr = [1,5,7,8]
let pointer = UnsafeMutablePointer<[Int]>.allocate(capacity: 4)
pointer.initialize(to: arr)
let x = pointer.pointee[3]
print(x)
pointer.deinitialize()
pointer.deallocate(capacity: 4)
class A {
var x: String?
convenience init (_ x: String) {
self.init()
self.x = x
}
func description() -> String {
return x ?? ""
}
}
let arr2 = [A("OK"), A("OK 2")]
let pointer2 = UnsafeMutablePointer<[A]>.allocate(capacity: 2)
pointer2.initialize(to: arr2)
pointer2.pointee
let y = pointer2.pointee[1]
print(y)
pointer2.deinitialize()
pointer2.deallocate(capacity: 2)
从原始源转换为 Swift 3.0