'bytes'不可用:改为使用withUnsafeBytes

Jam*_*son 11 nsdata ios swift

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

在此输入图像描述

这是我的代码:

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

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

Mar*_*n R 12

假设data有类型Data,以下应该工作:

let tempData: NSMutableData = NSMutableData(length: 26)!
data.withUnsafeBytes { 
    tempData.replaceBytes(in: NSMakeRange(0, data.count), withBytes: $0)
}
Run Code Online (Sandbox Code Playgroud)

使用

/// 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
Run Code Online (Sandbox Code Playgroud)

的方法Data.在闭包内部$0是一个UnsafePointer<Void> 字节(UnsafeRawPointer在Xcode 8 beta 6中).