使用Swift 5+将数据写入OutputStream [英] Writing Data to an OutputStream with Swift 5+

查看:386
本文介绍了使用Swift 5+将数据写入OutputStream的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这段代码曾经很好(就编译器而言,它并没有抱怨):

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)
        }
    }
}

从Swift 5.0开始,这会产生警告:

Since Swift 5.0, this produces a warning:

警告:不建议使用"withUnsafeBytes":请改用withUnsafeBytes<R>(_: (UnsafeRawBufferPointer) throws -> R) rethrows -> R

我尝试使用建议的方法,但似乎无法将UnsafeRawBufferPointer纠缠为OutputStream.write最终需要的UnsafePointer<UInt8>.

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?

推荐答案

诀窍是使用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上运行,但是显然存在一些问题;参见相关的论坛讨论.

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

这篇关于使用Swift 5+将数据写入OutputStream的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆