我正在使用SecRandomCopyBytes
生成一个安全的随机数。
有没有办法指定“范围”?
我需要获得这段Java
代码的相同行为:
SecureRandom r = new SecureRandom();
char x = (char)(r.nextInt(26) + 'a');
任何提示将不胜感激!
更新
看到我提出了一个愚蠢的问题,我觉得有必要分享解决方案,扩展 Int 类型:
public extension Int {
/**
Create a random num Int in range
:param: lower number Int
:param: upper number Int
:return: random number Int
*/
public static func random(#min: Int, max: Int) -> Int {
return Int(arc4random_uniform(UInt32(max - min + 1))) + min
}
/**
Create a secure random num Int in range
:param: lower number Int
:param: upper number Int
:return: random number Int
*/
public static func secureRandom(#min: Int, max: Int) -> Int {
if max == 0 {
NSException(name: "secureRandom", reason: "max number must be > 0", userInfo: nil).raise()
}
var randomBytes = UnsafeMutablePointer<UInt8>.alloc(8)
SecRandomCopyBytes(kSecRandomDefault, 8, randomBytes)
let randomNumber = unsafeBitCast(randomBytes, UInt.self)
return Int(randomNumber) % max + min
}
}