Writing Data to an OutputStream with Swift 5+

2019-08-18 06:15发布

问题:

This code used to be fine (in the sense that the compiler didn't complain):

extension OutputStream {
    func write(_ data: Data) -> Int {
        return data.withUnsafeBytes { pointer in
            return self.write(pointer, maxLength: data.count)
        }
    }
}

Since Swift 5.0, this produces a warning:

Warning: 'withUnsafeBytes' is deprecated: use withUnsafeBytes<R>(_: (UnsafeRawBufferPointer) throws -> R) rethrows -> R instead

I tried using the proposed method but I can't seem to wrangle the UnsafeRawBufferPointer into the UnsafePointer<UInt8> that OutputStream.write ultimately requires.

How can I write this function in a non-deprecated way?

回答1:

The trick is to use bindMemory function:

func write(_ data: Data) -> Int {
    return data.withUnsafeBytes({ (rawBufferPointer: UnsafeRawBufferPointer) -> Int in
        let bufferPointer = rawBufferPointer.bindMemory(to: UInt8.self)
        return self.write(bufferPointer.baseAddress!, maxLength: data.count)
    })
}

While this works with Swift 5.0, there are apparently some issues; see a related forum discussion.