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

Here's an example function that creates a random password with uppercase letters, lowercase letters, numbers and symbols using Swift:

main.swift
func generateRandomPassword(length: Int = 12) -> String {
    let uppercaseLetters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
    let lowercaseLetters = "abcdefghijklmnopqrstuvwxyz"
    let numbers = "0123456789"
    let symbols = "!@#$%^&*()_+-=[]{}|:;.,<>/?"
    
    let allowedChars = "\(uppercaseLetters)\(lowercaseLetters)\(numbers)\(symbols)"
    
    var result = ""
    for _ in 0 ..< length {
        let randomIndex = Int(arc4random_uniform(UInt32(allowedChars.count)))
        let randomChar = allowedChars[allowedChars.index(allowedChars.startIndex, offsetBy: randomIndex)]
        result.append(randomChar)
    }
    return result
}
635 chars
17 lines

You can call this function by passing in the desired length of the password as a parameter, like this:

main.swift
let password = generateRandomPassword(length: 16)
print(password)
// Example output: "fJ8K$yP%4M@u#9tW"
104 chars
4 lines

gistlibby LogSnag