Created
January 13, 2016 09:26
-
-
Save samuel-mellert/20b3c99dec168255a046 to your computer and use it in GitHub Desktop.
Creates a random alphanumeric string with a defined 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
// Swift 2 code | |
func randomString(length: Int) -> String { | |
let charactersString = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789" | |
let charactersArray = Array(arrayLiteral: charactersString) | |
var string = "" | |
for _ in 0..<length { | |
string += charactersArray[Int(arc4random()) % charactersArray.count] | |
} | |
return string | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
let charactersArray = Array(arrayLiteral: charactersString) returns an array with a single string element containing the contents of charactersString (i.e ["abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"]
To get an array of characters of charactersString, use Array(charactersString.characters).
Then, when adding the character to the output string, append the character.