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

Here is a code snippet in Swift for generating a random password with a custom length that contains both uppercase and lowercase letters:

main.swift
func generatePassword(length: Int) -> String {

    let letters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
    var password = ""

    for _ in 0..<length {
        let rand = Int(arc4random_uniform(UInt32(letters.count)))
        let nextChar = letters[letters.index(letters.startIndex, offsetBy: rand)]
        password += String(nextChar)
    }

    return password
}
384 chars
14 lines

To use this function, simply call it with the desired length parameter:

main.swift
let password = generatePassword(length: 10) // Returns a 10-character random password
86 chars
2 lines

This generates a random password consisting of lowercase and uppercase letters, with a length defined by the length parameter.

gistlibby LogSnag