create a password with symbols in swift

To create a password with symbols in Swift, we can use a random password generator function. Here's an example of a function that generates a random password with symbols:

main.swift
func generatePassword(length: Int) -> String {
    let allowedChars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890!@#$%^&*()_-+={}[]"
    let allowedCharsCount = UInt32(allowedChars.count)
    var password = ""

    for _ in 0..<length {
        let randomNum = Int(arc4random_uniform(allowedCharsCount))
        let randomIndex = allowedChars.index(allowedChars.startIndex, offsetBy: randomNum)
        let newChar = allowedChars[randomIndex]
        password += String(newChar)
    }

    return password
}
528 chars
15 lines

This function takes a parameter length that specifies the length of the password to be generated. It then defines a string allowedChars that contains all the characters that are allowed in the password, including symbols.

The function then loops length number of times, generating a random number between 0 and the number of allowed characters, and using that random number to select a random character from the allowedChars string.

Finally, the function returns the generated password.

To use this function and generate a password with symbols, you can simply call it with the desired length, like this:

main.swift
let password = generatePassword(length: 10)
print(password) // Example output: Jm9X^pt_#f
90 chars
3 lines

gistlibby LogSnag