NSData
aveva una struttura bytes
per accedere ai byte. Il nuovo tipo di valore Data
in Swift 3 ha invece un metodo , che chiama una chiusura con un puntatore ai byte.
Quindi questo è come si scrive Data
a un NSOutputStream
(senza fusione a NSData
):
let data = ... // a Data value
let bytesWritten = data.withUnsafeBytes { outputStream.write($0, maxLength: data.count) }
Note: withUnsafeBytes()
è un metodo generico:
/// 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
Nella chiamata sopra, sia ContentType
e ResultType
vengono automaticamente dedotto dalla compilatore (come UInt8
e Int
), rendendo aggiuntivi UnsafePointer()
conversioni inutili.
outputStream.write()
restituisce il numero di byte effettivamente scritto. Generalmente, è necessario il controllare il valore. Può essere -1
se l'operazione di scrittura non è riuscita o inferiore a data.count
quando si scrive in socket, pipe o altri oggetti con un controllo di flusso.
fonte
2016-06-29 06:53:47