问题描述
我想在Swift 3.0中使用SecRandomCopyBytes
生成随机字节.这是我在Swift 2.2中做到的方式
I want to generate random bytes using SecRandomCopyBytes
in Swift 3.0. Here is how I did it in Swift 2.2
private static func generateRandomBytes() -> String? {
let data = NSMutableData(length: Int(32))
let result = SecRandomCopyBytes(kSecRandomDefault, 32, UnsafeMutablePointer<UInt8>(data!.mutableBytes))
if result == errSecSuccess {
return data!.base64EncodedString(options: NSData.Base64EncodingOptions(rawValue: 0))
} else {
print("Problem generating random bytes")
return nil
}
}
在Swift 3中,我尝试这样做,因为我知道unsafemutablebytes的概念现在有所不同,但是它不允许我返回.如果我注释掉返回部分,它仍然显示Generic Parameter ResultType could not be inferred
In Swift 3, I tried to do it like this, since I know the concept of unsafemutablebytes is different now, but it doesn't allow me to return. If I comment out the return part, it still says Generic Parameter ResultType could not be inferred
fileprivate static func generateRandomBytes() -> String? {
var keyData = Data(count: 32)
_ = keyData.withUnsafeMutableBytes {mutableBytes in
let result = SecRandomCopyBytes(kSecRandomDefault, keyData.count, mutableBytes)
if result == errSecSuccess {
return keyData.base64EncodedString(options: NSData.Base64EncodingOptions(rawValue: 0))
} else {
print("Problem generating random bytes")
return nil
}
}
return nil
}
有人知道如何解决此问题吗?
Does anyone know how to fix this?
谢谢
推荐答案
您已关闭,但封闭中的return
返回从闭包开始,而不是从外部函数开始.因此,在SecRandomCopyBytes()
中仅应调用关闭,结果传回.
You were close, but return
inside the closure returnsfrom the closure, not from the outer function.Therefore only SecRandomCopyBytes()
should be called in theclosure, and the result passed back.
func generateRandomBytes() -> String? {
var keyData = Data(count: 32)
let result = keyData.withUnsafeMutableBytes {
(mutableBytes: UnsafeMutablePointer<UInt8>) -> Int32 in
SecRandomCopyBytes(kSecRandomDefault, 32, mutableBytes)
}
if result == errSecSuccess {
return keyData.base64EncodedString()
} else {
print("Problem generating random bytes")
return nil
}
}
对于单表达式闭包",可以推断出闭包类型自动,因此可以缩短为
For a "single-expression closure" the closure type can inferredautomatically, so this can be shortened to
func generateRandomBytes() -> String? {
var keyData = Data(count: 32)
let result = keyData.withUnsafeMutableBytes {
SecRandomCopyBytes(kSecRandomDefault, 32, $0)
}
if result == errSecSuccess {
return keyData.base64EncodedString()
} else {
print("Problem generating random bytes")
return nil
}
}
迅速5更新:
func generateRandomBytes() -> String? {
var keyData = Data(count: 32)
let result = keyData.withUnsafeMutableBytes {
SecRandomCopyBytes(kSecRandomDefault, 32, $0.baseAddress!)
}
if result == errSecSuccess {
return keyData.base64EncodedString()
} else {
print("Problem generating random bytes")
return nil
}
}
这篇关于在Swift中使用SecRandomCopyBytes的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!