这段代码曾经很好(在某种意义上,编译器没有抱怨):
extension OutputStream { func write(_ data: Data) -> Int { return data.withUnsafeBytes { pointer in return self.write(pointer, maxLength: data.count) } } }
从Swift 5.0开始,这会产生警告:
警告:不建议使用“ withUnsafeBytes”:请withUnsafeBytes<R>(_: (UnsafeRawBufferPointer) throws -> R) rethrows -> R改用
withUnsafeBytes<R>(_: (UnsafeRawBufferPointer) throws -> R) rethrows -> R
我试着用所提出的方法,但我似乎无法缠斗UnsafeRawBufferPointer到UnsafePointer<UInt8>这OutputStream.write最终需要。
UnsafeRawBufferPointer
UnsafePointer<UInt8>
OutputStream.write
如何以不推荐的方式编写此函数?
诀窍是使用bindMemory函数:
bindMemory
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) }) }
尽管此功能适用于Swift 5.0,但显然存在一些问题。参见相关论坛讨论。