Daniel Daniel - 1 month ago 23
Swift Question

Swift language: How to call SecRandomCopyBytes

From Objective-C, I could do this:

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


When attempting this in Swift, I have the following:

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


but I get this compiler error:

'Void' is not identical to 'UInt8'


The data.mutableBytes parameter is rejected because the types do not match, but I can't figure out how to coerce the parameter (and I'm presuming it's somehow safe to do).

Answer

This appears to work:

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