在Swift 3中将数据写入NSOutputStream [英] Writing Data to an NSOutputStream in Swift 3
问题描述
此问题的解决方案不再适用雨燕3.
不再有Data
的属性bytes
(以前是NSData
.
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()
是通用方法:
Remarks:
withUnsafeBytes()
is a generic method:
/// 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
在上述通话中,
ContentType
和ResultType
都会自动被
编译器(如UInt8
和Int
),从而增加了
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屋!