内存分配

基本类型 / 指针

//一次为多个值分配内存
let count = 3
let buffer = UnsafeMutablePointer<Int>.allocate(
    capacity: count)
buffer.initialize(repeating: 0, count: count)

for i in 0 ..< count {
    buffer[i] = (i + 1) * 10
}
//buffer[1] is 20
print("buffer[1] is \(buffer[1])")

//原始内存对类型一无所知:
//申请的只是字节数和对齐方式
let raw = UnsafeMutableRawPointer.allocate(
    byteCount: 8, alignment: 8)
raw.storeBytes(of: 42, as: Int.self)
let stored = raw.load(as: Int.self)
//stored is 42
print("stored is \(stored)")

//这里不会自动释放任何内容
buffer.deinitialize(count: count)
buffer.deallocate()
raw.deallocate()
print("memory is released")