gpt4 book ai didi

ios - 在 Swift 中使用 SecRandomCopyBytes

转载 作者:IT王子 更新时间:2023-10-29 05:28:35 28 4
gpt4 key购买 nike

我想在 Swift 3.0 中使用 SecRandomCopyBytes 生成随机字节。这是我在 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

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
}

有人知道如何解决这个问题吗?

谢谢

最佳答案

你很接近,但是闭包内的 return 返回来自闭包,而不是来自外部函数。因此只有 SecRandomCopyBytes() 应该在关闭,返回结果。

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

对于“单表达式闭包”,可以推断出闭包类型自动,所以这可以缩短为

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

Swift 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
}
}

关于ios - 在 Swift 中使用 SecRandomCopyBytes,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39820602/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com