2016-08-16 28 views
8

代码先前在雨燕2.2的工作现在抛出下面的错误在斯威夫特3:“字节”是不可用:使用withUnsafeBytes代替

enter image description here

这里是我的代码:

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

我应该如何替换“data.bytes”以修复错误?我已经尝试过实施'withUnsafeBytes'并查看了Apple的文档,但无法摆脱它的困扰!

+0

你还没有提供'data'的来源,但是如果你可以把它转换成'Data',这将会更加简单,你不需要在'NSMutableData'和'Data'之间进行桥接。你只需使用'replaceSubrange'。 –

回答

9

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

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

使用的Data

/// 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 

方法。封闭内部$0UnsafePointer<Void> 到字节(Xcode 8 beta 6中的UnsafeRawPointer)。

+0

你能更新答案为swift 3.0 –

+0

@TejasArdeshna:*是* Swift 3. –

+0

为什么长度硬编码为26?它会对大数据造成什么问题吗?我是ios的新手,只是确认。 –