Luca Davanzo Luca Davanzo - 2 months ago 19
Swift Question

Generate random number in range with SecRandomCopyBytes

I'm using

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
}
}

Answer

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
Comments