NSData
具有bytes
访问字节的属性。Swift 3 中的新Data
值类型有一个withUnsafeBytes()
方法,它使用指向字节的指针调用闭包。
所以这就是你写Data
一个NSOutputStream
(不强制转换为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
在上面的调用中,ContentType
编译ResultType
器会自动推断出 和 (作为UInt8
和Int
),因此
UnsafePointer()
不需要额外的转换。
outputStream.write()
返回实际写入的字节数。通常,您应该检查该值。-1
如果写入操作失败,或者data.count
写入套接字、管道或其他具有流控制的对象时失败,则可能会失败。