create a password with a custom length and numbers in swift

You can generate a random password in Swift by defining a string that contains all the possible characters that you want to include. You can then use the arc4random_uniform() function to pick random characters from this string.

Here's an example of how you can generate a random password with a custom length and including random numbers:

func generateRandomPassword(length: Int) -> String {
    let allowedChars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890"
    let allowedCharsCount = UInt32(allowedChars.count)
    var randomPassword = ""

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

    return randomPassword
536 chars
15 lines

This function takes a single parameter length which specifies the length of the password you want to generate. The allowedChars string contains all the characters that you wish to include in the password. In this case, it includes all the alphabets (lowercase and uppercase) and digits from 0 to 9.

The function then loops through the allowed characters for the specified length and randomly selects a character each time. This character is then appended to the randomPassword variable.

Finally, once the loop is complete, the generated password is returned.

You can use this function as follows:

let password = generateRandomPassword(length: 12) // generates a random password with length 12
96 chars
2 lines

gistlibby LogSnag