Search code examples
swiftswift3unsafe-pointers

Error in UnsafeMutablePointer in swift3


My codd look like this

let samples = UnsafeMutableBufferPointer<Int16>(start:UnsafeMutablePointer(buffer.mData), count: Int(buffer.mDataByteSize)/sizeof(Int16))

While running this code is generating the following error

Cannot invoke initializer for type 'UnsafeMutablePointer<_>' with an argument list of type '(UnsafeMutableRawPointer?)'

buffer.mdata is having raw data. How can I solve this issue. Thanks in advance


Solution

  • Assuming that buffer is a AudioBuffer from the AVFoundation framework: buffer.mData is a "optional raw pointer" UnsafeMutableRawPointer?, and in Swift 3 you have to bind the raw pointer to a typed pointer:

    let buffer: AudioBuffer = ...
    
    if let mData = buffer.mData {
        let numSamples = Int(buffer.mDataByteSize)/MemoryLayout<Int16>.size
        let samples = UnsafeMutableBufferPointer(start: mData.bindMemory(to: Int16.self, capacity: numSamples),
                                                 count: numSamples)
        // ...
    }
    

    See SE-0107 UnsafeRawPointer API for more information about raw pointers.