'bytes' 不可用:改用 withUnsafeBytes

'bytes' is unavailable: use withUnsafeBytes instead

以前在 Swift 2.2 中运行的代码现在在 Swift 3 中抛出以下错误:

这是我的代码:

let tempData: NSMutableData = NSMutableData(length: 26)!
tempData.replaceBytes(in: NSMakeRange(0, data.count), withBytes:data.bytes)

我应该用什么替换 "data.bytes" 来修复错误?我已经尝试实施 'withUnsafeBytes' 并查看了 Apple 的文档,但无法理解它!

假设 data 的类型为 Data,以下应该有效:

let tempData: NSMutableData = NSMutableData(length: 26)!
data.withUnsafeBytes { 
    tempData.replaceBytes(in: NSMakeRange(0, data.count), withBytes: [=10=])
}

使用

/// 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 的方法。在闭包 [=15=] 内是一个 UnsafePointer<Void> 到字节(Xcode 8 beta 6 中的UnsafeRawPointer)。

用这个 :

        let data:Data = Data()
        let myDataBytes = data.withUnsafeBytes {_ in
            UnsafePointer<UInt8>(data.withUnsafeBytes({
                [=10=]
            }))
        }
        let writtenBytes = writeStream.write(.init(myDataBytes), maxLength: data.count)