在介绍指针使用有必要介绍下一个枚举那就是
分别是返回类型T占用内存大小,在连续储存空间中2个实例的距离,对齐方式。
MemoryLayout:有3个常用方法
MemoryLayout<T>.size,
MemoryLayout<T>.stride,
MemoryLayout<T>.alignment
分别是返回类型T占用内存大小,在连续储存空间中2个实例的距离,对齐方式。
看下面例子
MemoryLayout<Double>.size // 8
MemoryLayout<Double>.stride //8
MemoryLayout<Double>.alignment //8
MemoryLayout<Bool>.size //1
MemoryLayout<Bool>.stride //1
MemoryLayout<Bool>.alignment//1
struct Example {
let x: Double
let y: Double
let isHave: Bool
}
MemoryLayout<Example>.size//17
MemoryLayout<Example>.stride//24
MemoryLayout<Example>.alignment//8
这个枚举在创建原始指针分配内存中非常有用。
UnsafeMutableRawPointer.allocate(bytes: MemoryLayout<Example>.stride, alignedTo: MemoryLayout<Example>.alignment)