create a password with uppercase, lowercase letters and numbers in swift

To create a password in Swift that includes uppercase and lowercase letters as well as numbers, you can use the arc4random_uniform() function to generate random numbers and then convert those numbers to characters in the ASCII table.

Here is an example function that will generate a random password with a length of length:

main.swift
func generatePassword(length: Int) -> String {
    let uppercaseLetters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
    let lowercaseLetters = "abcdefghijklmnopqrstuvwxyz"
    let numbers = "0123456789"

    var password = ""
    
    // add at least one uppercase letter
    password.append(uppercaseLetters.randomElement()!)

    // add at least one lowercase letter
    password.append(lowercaseLetters.randomElement()!)
    
    // add at least one number
    password.append(numbers.randomElement()!)

    // add remaining characters
    for _ in 0 ..< length - 3 {
        let pool = [uppercaseLetters, lowercaseLetters, numbers]
        let randomPool = pool.randomElement()!
        let randomIndex = Int(arc4random_uniform(UInt32(randomPool.count)))
        let randomCharacter = randomPool[randomIndex]
        password.append(randomCharacter)
    }
    
    return password
}
874 chars
28 lines

This function creates three strings: one for uppercase letters, one for lowercase letters, and one for numbers. It initializes an empty string for the password, and then adds one random uppercase letter, lowercase letter, and number to the password. The remaining characters are then randomly selected from the three pools and added to the password until the specified length is reached.

It's worth noting that this password generator does not include special characters. Including special characters can make the password more secure, but may also make it more difficult to remember. Additionally, this function does not handle any form of password policy, like disallowing common dictionary words.

gistlibby LogSnag