Writing Data to an OutputStream with Swift 5+

百般思念 提交于 2019-12-18 09:34:38

问题


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.



来源:https://stackoverflow.com/questions/55829812/writing-data-to-an-outputstream-with-swift-5

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!