xcode 如何在 Swift 3 中使用 UnsafeMutablePointer?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/39515173/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to use UnsafeMutablePointer in Swift 3?
提问by AppreciateIt
I have the following code written in Swift 2.2:
我有以下用 Swift 2.2 编写的代码:
let keyData = NSMutableData(length: 64)!
SecRandomCopyBytes(kSecRandomDefault, 64, UnsafeMutablePointer<UInt8>(keyData.mutableBytes))
XCode 8 highlights that second line and claims that
XCode 8 突出显示了第二行并声称
Cannot invoke initializer for type 'UnsafeMutablePointer<_>' with an argument list of type '(UnsafeMutableRawPointer)'
无法使用类型为“(UnsafeMutableRawPointer)”的参数列表调用类型“UnsafeMutablePointer<_>”的初始化程序
While I appreciate XCode telling me this, I don't quite understand how to change the UnsafeMutableRawPointer to be acceptable.
虽然我很欣赏 XCode 告诉我这一点,但我不太明白如何将 UnsafeMutableRawPointer 更改为可接受的。
Does anyone know how to convert this code into Swift 3?
有谁知道如何将此代码转换为 Swift 3?
回答by OOPer
I recommend you to work with Data
rather than NSData
in Swift 3.
我建议您使用Swift 3Data
而不是NSData
Swift 3。
var keyData = Data(count: 64)
let result = keyData.withUnsafeMutableBytes {mutableBytes in
SecRandomCopyBytes(kSecRandomDefault, keyData.count, mutableBytes)
}
withUnsafeMutableBytes(_:)
is declared as a generic method, so, in simple cases such as this, you can use it without specifying element type.
withUnsafeMutableBytes(_:)
被声明为泛型方法,因此,在诸如此类的简单情况下,您可以在不指定元素类型的情况下使用它。