Swift语言:如何调用SecRandomCopyBytes

时间:2014-08-27 00:49:44

标签: ios xcode swift xcode6

从Objective-C,我可以这样做:

NSMutableData *data = [NSMutableData dataWithLength:length];
int result = SecRandomCopyBytes(kSecRandomDefault, length, data.mutableBytes);

在Swift中尝试此操作时,我有以下内容:

let data = NSMutableData(length: Int(length))
let result = SecRandomCopyBytes(kSecRandomDefault, length, data.mutableBytes)

但是我得到了这个编译错误:

'Void' is not identical to 'UInt8'

data.mutableBytes参数被拒绝,因为类型不匹配,但我无法弄清楚如何强制参数(我假设它在某种程度上是安全的)。

3 个答案:

答案 0 :(得分:13)

这似乎有效:

let data = NSMutableData(length: Int(length))
let result = SecRandomCopyBytes(kSecRandomDefault, length, UnsafeMutablePointer<UInt8>(data.mutableBytes))

答案 1 :(得分:9)

Swift 5

var data = Data(count: <count>)
let result = data.withUnsafeMutableBytes {    
    SecRandomCopyBytes(kSecRandomDefault, data.count, $0.baseAddress!) 
}

Swift 4

var data = Data(count: <count>)
let result = data.withUnsafeMutableBytes { mutableBytes in
    SecRandomCopyBytes(kSecRandomDefault, data.count, mutableBytes)
}

答案 2 :(得分:3)

Swift 4版本:

let count = 16
var data = Data(count: count)
_ = data.withUnsafeMutableBytes {
    SecRandomCopyBytes(kSecRandomDefault, count, $0)
}