create a password with uppercase letters in swift

You can create a password with uppercase letters in Swift by generating a random string of characters that includes uppercase letters. Here's an example function that creates a password string with uppercase letters:

main.swift
func generatePassword(length: Int) -> String {
    let uppercaseLetters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
    let allLetters = "abcdefghijklmnopqrstuvwxyz" + uppercaseLetters + "0123456789"
    var password = ""
    for _ in 0..<length {
        let randomIndex = Int.random(in: 0..<allLetters.count)
        let randomCharacter = allLetters[allLetters.index(allLetters.startIndex, offsetBy: randomIndex)]
        password.append(randomCharacter)
    }
    return password
}
472 chars
12 lines

You can call this function and specify the desired length of the password:

main.swift
let password = generatePassword(length: 10)
print(password) // Example output: "S7lQ2T1A9f"
92 chars
3 lines

In this example, the function defines two string variables uppercaseLetters and allLetters, where uppercaseLetters includes all uppercase letters and allLetters includes all uppercase and lowercase letters as well as digits.

The function then uses a loop to randomly select characters from this pool of letters and appends them to the password string until the desired length is reached. Finally, the function returns the generated password string.

gistlibby LogSnag