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
),使得額外的 轉換不必要。
outputStream.write()
返回實際寫入的字節數。 一般來說,你應該檢查那個值。如果 寫入操作失敗,則可以爲-1
;如果將 寫入套接字,管道或其他具有流量控制的對象,則該值可能小於data.count
。