我想在
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的概念现在不同了,但它不允许我返回.如果我注释掉返回部分,它仍然说无法推断通用参数ResultType
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 }
有谁知道如何解决这一问题?
谢谢
解决方法
你很接近,但在关闭内部返回
从封闭,而不是从外部功能.
因此,只应在中调用SecRandomCopyBytes()
关闭,结果传回来.
从封闭,而不是从外部功能.
因此,只应在中调用SecRandomCopyBytes()
关闭,结果传回来.
func generateRandomBytes() -> String? { var keyData = Data(count: 32) let result = keyData.withUnsafeMutableBytes { (mutableBytes: UnsafeMutablePointer<UInt8>) -> Int32 in SecRandomCopyBytes(kSecRandomDefault,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,$0) } if result == errSecSuccess { return keyData.base64EncodedString() } else { print("Problem generating random bytes") return nil } }