Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Creates a random alphanumeric string with a defined length.
// 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
}
@gingofthesouth

This comment has been minimized.

Copy link

@gingofthesouth gingofthesouth commented Apr 5, 2016

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.

func randomString(length: Int) -> String {
    let charactersString = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
    let charactersArray : [Character] = Array(charactersString.characters)

    var string = ""
    for _ in 0..<length {
        string.append(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