I'm using SecRandomCopyBytes
for generate a secure random number.
Is there a way to specify a "range"?
I need to obtain the same behaviour of this Java
piece of code:
SecureRandom r = new SecureRandom();
char x = (char)(r.nextInt(26) + 'a');
Any tips will appreciate!
UPDATE
Seeing that I made a silly question I feel compelled to share the solution, made extending Int type:
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
}
}
Edit: Swift 4.2 allows to generate random numbers using Int
class:
let randomNumber = Int.random(in: 0 ..< 26)
The random source should be cryptographically secure SystemRandomNumberGenerator
See also:
Old answer: iOS 9 introduced GameplayKit which provides SecureRandom.nextInt()
Java equivalent.
To use it in Swift 3 :
import GameplayKit
// get random Int
let randomInt = GKRandomSource.sharedRandom().nextInt(upperBound: 26)
See this answer for more info: https://stackoverflow.com/a/31215189/1245231
You can always specify a range by applying modulo and addition, check this pseudocode:
// random number in the range 1985-2014
r = rand() % 30 + 1985
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.