create a password with uppercase letters and lowercase letters in swift

Here's a function in Swift that generates a random password including uppercase letters, lowercase letters, and numbers:

main.swift
func generatePassword(length: Int) -> String {
    let letters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
    let numbers = "0123456789"
    var password = ""
    
    for _ in 0..<length {
        let randomIndex = Int(arc4random_uniform(UInt32(letters.count + numbers.count)))
        if randomIndex < letters.count {
            let randomLetterIndex = letters.index(letters.startIndex, offsetBy: randomIndex)
            password.append(letters[randomLetterIndex])
        } else {
            let randomNumberIndex = numbers.index(numbers.startIndex, offsetBy: randomIndex - letters.count)
            password.append(numbers[randomNumberIndex])
        }
    }
    
    return password
}
708 chars
19 lines

You can call this function with an integer argument to specify the length of the password you want to generate, like this:

main.swift
let password = generatePassword(length: 10)
print(password) // e.g. "Gb71pR9FkT"
81 chars
3 lines

gistlibby LogSnag