Created
July 24, 2017 13:20
-
-
Save migueltg/cc0ea8be6d6a1fc8332b0cfca35e3c1c to your computer and use it in GitHub Desktop.
Generate random string with custom length
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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