这个问题的解决方案不再适用于Swift 3。
不再有一个属性bytes的Data(前身NSData。
bytes
Data
NSData
let data = dataToWrite.first! self.outputStream.write(&data, maxLength: data.count)
有了这段代码,我得到了错误:
Cannot convert value of type 'Data' to expected argument type 'UInt8'
你怎么能写Data一NSOutputStream斯威夫特3?
NSOutputStream
NSData具有bytes访问字节的属性。DataSwift 3中的新值类型具有一个withUnsafeBytes() 方法,该方法调用带有指向字节的指针的闭包。
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都是由编译器自动推断的(as UInt8和Int),从而UnsafePointer()无需进行其他 转换。
ContentType
ResultType
UInt8
Int
UnsafePointer()
outputStream.write()返回实际写入的字节数。通常,您应该 检查 该值。可能是-1写入操作失败,还是少于data.count写入带有流控制的套接字,管道或其他对象时的失败。
outputStream.write()
-1
data.count