假设 data
的类型为 Data
,以下代码应该可以正常工作:
let tempData: NSMutableData = NSMutableData(length: 26)!
data.withUnsafeBytes {
tempData.replaceBytes(in: NSMakeRange(0, data.count), withBytes: $0)
}
使用
/// 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
Data
的方法。在闭包内部,$0
是一个指向字节的 UnsafePointer<Void>
(在 Xcode 8 beta 6 中是 UnsafeRawPointer
)。
使用这个:
let data:Data = Data()
let myDataBytes = data.withUnsafeBytes {_ in
UnsafePointer<UInt8>(data.withUnsafeBytes({
$0
}))
}
let writtenBytes = writeStream.write(.init(myDataBytes), maxLength: data.count)
data
的来源,但如果你能将其转换为Data
,这将会更简单,而且你也不需要在NSMutableData
和Data
之间进行桥接。你只需要使用replaceSubrange
即可。 - Rob Napier