Skip to content

Instantly share code, notes, and snippets.

@joanmolinas
Last active August 29, 2015 14:17
Show Gist options
  • Save joanmolinas/70bdc3615cb9ae392fd2 to your computer and use it in GitHub Desktop.
Save joanmolinas/70bdc3615cb9ae392fd2 to your computer and use it in GitHub Desktop.
extension Float {
static func randomFloat(range : ClosedInterval<Float>) -> Float {
return range.start + (range.end - range.start) * Float(Float(arc4random()) / Float(UInt32.max))
}
}
extension Int {
static func randomInt(range : ClosedInterval<Int>) -> Int {
return range.start + Int(arc4random_uniform(UInt32(range.end - range.start + 1)))
}
}
extension Double {
static func randomDouble(range : ClosedInterval<Double>) -> Double {
return range.start + (range.end - range.start) * Double(Double(arc4random()) / Double(UInt32.max))
}
}
extension String {
static func randomString(length : Int) -> String {
let characters : NSString = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
var mutableString = NSMutableString(capacity: length)
for var i = 0; i < length; i++ {
mutableString.appendFormat("%C", characters.characterAtIndex(Int(arc4random_uniform(UInt32 (characters.length)))))
}
return mutableString
}
}
Float.randomFloat(1.3...5.6) //Output -> 2.56939077377319
Int.randomInt(1...6) // Output -> 3
Double.randomDouble(1.6...9.8) //Output -> 3.9534583365902
String.randomString(10) // Output -> 5A2SZGEpwc
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment