'bytes'不可用:改为使用withUnsafeBytes [英] 'bytes' is unavailable: use withUnsafeBytes instead

查看:1860
本文介绍了'bytes'不可用:改为使用withUnsafeBytes的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Code that was previously working in Swift 2.2 is now throwing the following error in Swift 3:

这是我的代码:

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

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

What should I replace "data.bytes" with to fix the error? I've tried implementing 'withUnsafeBytes' and had a look at Apple's documentation, but can't get my head around it!

推荐答案

假设数据的类型为数据,则以下内容应该有效:

Assuming that data has type Data, the following should work:

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

数据的方法。在闭包内 $ 0 是一个 UnsafePointer< Void>
到字节( Xcode 8 beta 6中的UnsafeRawPointer

method of Data. Inside the closure $0 is a UnsafePointer<Void> to the bytes (UnsafeRawPointer in Xcode 8 beta 6).

这篇关于'bytes'不可用:改为使用withUnsafeBytes的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆