'字节'不可用:改为使用withUnsafeBytes

时间:2016-08-16 16:03:44

标签: ios swift nsdata

之前在Swift 2.2中工作的代码现在在Swift 3中引发了以下错误:

enter image description here

这是我的代码:

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

我应该更换什么" data.bytes"用来修复错误?我已经尝试过使用不安全互联网'并查看了Apple的文档,但无法理解它!

1 个答案:

答案 0 :(得分:11)

假设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)。