create a password with a custom length and uppercase letters in swift

Here's an example function in Swift that generates a random password with a custom length and includes uppercase letters:

func generatePassword(length: Int) -> String {
    let uppercaseLetters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
    let allLetters = "abcdefghijklmnopqrstuvwxyz" + uppercaseLetters + "0123456789"
    var password = ""
    for _ in 0 ..< length {
        let randomIndex = Int(arc4random_uniform(UInt32(allLetters.count)))
        let randomLetter = allLetters[randomIndex]
        password += String(randomLetter)
    return password
443 chars
14 lines

To use this function:

let password = generatePassword(length: 10)
print(password) // ex: "5HTcU6j2Kf"
80 chars
3 lines

In the above function length parameter is the desired length of the password. uppercaseLetters constant contains all uppercase letters a .. z, allLetters constant includes both uppercase and lowercase letters along with digits 0-9. We then use a loop to generate a random index between 0 and the count of allLetters and append the corresponding letter to the password string. Finally, the password string is returned.

gistlibby LogSnag