Skip to content

Instantly share code, notes, and snippets.

@migueltg
Created July 24, 2017 13:20
Show Gist options
  • Save migueltg/cc0ea8be6d6a1fc8332b0cfca35e3c1c to your computer and use it in GitHub Desktop.
Save migueltg/cc0ea8be6d6a1fc8332b0cfca35e3c1c to your computer and use it in GitHub Desktop.
Generate random string with custom length
extension String {
static func random(_ length: Int = 20) -> String {
let base = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
var randomString: String = ""
for _ in 0..<length {
let randomValue = arc4random_uniform(UInt32(base.characters.count))
randomString += "\(base[base.characters.index(base.startIndex, offsetBy: Int(randomValue))])"
}
return randomString
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment