Quick 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 trying 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 cannot figure out how to force the parameter (and I assume that it is somehow safe).

+7
source share
3 answers

It works:

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

Swift 5

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

Swift 4 :

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

Swift 4 Version:

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

Source: https://habr.com/ru/post/1201198/


All Articles