How do I convert an array UnsafePointer<DSPComplex>
to an array of Floats in Swift?
I have seen this page, but because I am new to swift I don't have a clue on how to do it for an array of floats.
The DSPComplex is a structure containing an imaginary and real Float value. That's two floats. It cannot be converted to an array of Floats. However you must convert it to an UnsafeBufferPointer first and then you can pass it to an Array. Then you have a Swift array of DSPComplex structures.
func arrayForDSPComplex(pointer: UnsafePointer<DSPComplex>, count: Int) -> [DSPComplex] {
let buffer = UnsafeBufferPointer<DSPComplex>(start: pointer, count: count)
return Array(buffer)
}
You can even generalize it using generics if you want.
func arrayForPointer<T>(_ pointer: UnsafePointer<T>, count: Int) -> [T] {
let buffer = UnsafeBufferPointer(start: pointer, count: count)
return Array(buffer)
}
For mutable pointers you need another function.
func mutableArrayForPointer<T>(_ pointer: UnsafeMutablePointer<T>, count: Int) -> [T] {
let buffer = UnsafeMutableBufferPointer(start: pointer, count: count)
return Array(buffer)
}
You can improve it a little bit, by putting the functions as extensions on the pointer types.
extension UnsafePointer {
func arrayCopying(elementCount: Int) -> [Pointee] {
let buffer = UnsafeBufferPointer(start: self, count: elementCount)
return Array(buffer)
}
}
extension UnsafeMutablePointer {
func arrayCopying(elementCount: Int) -> [Pointee] {
let buffer = UnsafeMutableBufferPointer(start: self, count: elementCount)
return Array(buffer)
}
}
``