Skip to content

Instantly share code, notes, and snippets.

@dduan
Created October 17, 2015 20:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dduan/2c7a2c77d96d21e67eae to your computer and use it in GitHub Desktop.
Save dduan/2c7a2c77d96d21e67eae to your computer and use it in GitHub Desktop.
An extension on Int to generate random Ints and alphanumeric strings.
extension Int {
func asUpperBoundForRandom() -> Int {
return Int(arc4random_uniform(UInt32(self)))
}
func asLengthForRandomAlphanumeric() -> String {
let alphabet = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789".characters
var chars: [Character] = []
for _ in 1...self {
let randomIndex = alphabet.startIndex.advancedBy(alphabet.count.asUpperBoundForRandom())
chars.append(alphabet[randomIndex])
}
return String(chars)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment