如何在Swift 3中使用UnsafeMutablePointer? [英] How to use UnsafeMutablePointer in Swift 3?

查看:726
本文介绍了如何在Swift 3中使用UnsafeMutablePointer?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Swift 2.2中编写了以下代码:

I have the following code written in Swift 2.2:

let keyData = NSMutableData(length: 64)!
SecRandomCopyBytes(kSecRandomDefault, 64, UnsafeMutablePointer<UInt8>(keyData.mutableBytes))

XCode 8突出显示第二行和声明

XCode 8 highlights that second line and claims that


无法使用
参数列表调用类型'UnsafeMutablePointer< _>'的初始值设定项type'(UnsafeMutableRawPointer)'

Cannot invoke initializer for type 'UnsafeMutablePointer<_>' with an argument list of type '(UnsafeMutableRawPointer)'

虽然我很欣赏XCode告诉我这个,但我不太明白如何将UnsafeMutableRawPointer更改为可以接受。

While I appreciate XCode telling me this, I don't quite understand how to change the UnsafeMutableRawPointer to be acceptable.

有谁知道如何将此代码转换为Swift 3?

Does anyone know how to convert this code into Swift 3?

推荐答案

我建议你在Swift 3中使用数据而不是 NSData

I recommend you to work with Data rather than NSData in Swift 3.

var keyData = Data(count: 64)
let result = keyData.withUnsafeMutableBytes {mutableBytes in
    SecRandomCopyBytes(kSecRandomDefault, keyData.count, mutableBytes)
}

withU nsafeMutableBytes(_:)被声明为泛型方法,因此,在这种情况下,您可以在不指定元素类型的情况下使用它。

withUnsafeMutableBytes(_:) is declared as a generic method, so, in simple cases such as this, you can use it without specifying element type.

这篇关于如何在Swift 3中使用UnsafeMutablePointer?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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