create a password with a custom length and symbols in swift

Here's a code snippet that generates a random password with a customizable length and the option to include symbols:

main.swift
func generateRandomPassword(length: Int, includeSymbols: Bool) -> String {
    let letters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
    let symbols = "!@#$%^&*()_-+={}[]|<>,.?/~"
    
    var characterSet = Array(letters)
    
    // add symbols to character set if includeSymbols is true
    if includeSymbols {
        characterSet += Array(symbols)
    }
    
    var password = ""
    for _ in 0..<length {
        let randomIndex = Int(arc4random_uniform(UInt32(characterSet.count)))
        password.append(characterSet[randomIndex])
    }
    
    return password
}

// usage:
let password = generateRandomPassword(length: 12, includeSymbols: true)
print(password) // example output: "uI7}@$f^km~" 
732 chars
24 lines

This function uses a character set that includes lowercase and uppercase letters and digits by default. If includeSymbols is set to true, the function also adds a set of special characters to the character set.

Then, the function loops for the specified length of the password, each time generating a random index within the bounds of the character set and appending the corresponding character to the password string.

Note that this implementation uses arc4random_uniform() from the Foundation framework to generate random indices, which is a secure way to generate random numbers.

gistlibby LogSnag