在 Swift 3 中将数据写入 NSOutputStream [英] Writing Data to an NSOutputStream in Swift 3

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

问题描述

这个问题的解决方案不再适用斯威夫特 3.

The solution of this question no longer works with Swift 3.

不再有Data(以前的NSData)的bytes属性.

There is no longer a property bytes of Data (formerly NSData.

let data = dataToWrite.first!
self.outputStream.write(&data, maxLength: data.count)

使用此代码,我收到错误:

With this code, I get the error:

Cannot convert value of type 'Data' to expected argument type 'UInt8'

如何在 Swift 3 中将 Data 写入 NSOutputStream?

How can you write Data to an NSOutputStream in Swift 3?

推荐答案

NSData 有一个 bytes 属性来访问字节.Swift 3 中新的 Data 值类型有一个 withUnsafeBytes()方法代替,它调用带有指向字节的指针的闭包.

NSData had a bytes property to access the bytes. The new Data value type in Swift 3 has a withUnsafeBytes() method instead, which calls a closure with a pointer to the bytes.

这就是你如何将 Data 写入 NSOutputStream(不强制转换为 NSData):

So this is how you write Data to an NSOutputStream (without casting to NSData):

let data = ... // a Data value
let bytesWritten = data.withUnsafeBytes { outputStream.write($0, maxLength: data.count) }

<小时>

备注:withUnsafeBytes() 是一个通用方法:

/// Access the bytes in the data.
///
/// - warning: The byte pointer argument should not be stored and used outside of the lifetime of the call to the closure.
public func withUnsafeBytes<ResultType, ContentType>(_ body: @noescape (UnsafePointer<ContentType>) throws -> ResultType) rethrows -> ResultType

在上面的调用中,ContentTypeResultType 都是由编译器(如 UInt8Int),使额外的UnsafePointer() 不需要转换.

In the above call, both ContentType and ResultType are automatically inferred by the compiler (as UInt8 and Int), making additional UnsafePointer() conversions unnecessary.

outputStream.write() 返回实际写入的字节数.通常,您应该检查该值.它可以是 -1 如果写操作失败,或者写时小于data.count到套接字、管道或其他具有流量控制的对象.

outputStream.write() returns the number of bytes actually written. Generally, you should check that value. It can be -1 if the write operation failed, or less than data.count when writing to sockets, pipes, or other objects with a flow control.

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

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