withUnsafe(Mutable)BufferPointer()
можно использовать для получения указателя на (изменяемое) хранилище массива, а withMemoryRebound()
для доступа к массиву Float
в виде массива float4
:
func sumFloats(y: inout [Float], x: [Float], yc: Int, a: Float) {
let theA = simd_float4(a, a, a, a)
x.withUnsafeBufferPointer {
$0.baseAddress!.withMemoryRebound(to: simd_float4.self, capacity: yc / 4) { theX in
y.withUnsafeMutableBufferPointer {
$0.baseAddress!.withMemoryRebound(to: simd_float4.self, capacity: yc / 4) { theY in
for t in 0..<yc/4 {
theY[t] = theA * theX[t]
}
}
}
}
}
}
Пример:
let x: [Float] = [1, 2, 3, 4, 5, 6, 7, 8]
var y: [Float] = [0, 0, 0, 0, 0, 0, 0, 0]
sumFloats(y: &y, x: x, yc: 8, a: 2.0)
print(y) // [2.0, 4.0, 6.0, 8.0, 10.0, 12.0, 14.0, 16.0]