6
我想在Swift 3.0中使用SecRandomCopyBytes
生成隨機字節。這裏是我是如何做的雨燕在2.2在Swift 3.0中生成隨機字節
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
}
}
在斯威夫特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
}
有誰知道如何解決這一問題?
感謝
由於這個工作 – hockeybro