Generate random password in Swift

In this Swift programming tutorial, I am going to let you know how to generate a random password in Swift programming. So let’s continue.

Here we are going to create a simple function that will take the length of the password as the input parameter and return the password generated in the function.

Below is our Swift code for the random password generator:

func randomPassword(pwdLength: Int) -> String {
    let pwdLetters = "[email protected]#$%&()0123456789"
    var passWord = ""
    for _ in 0 ..< pwdLength {
        passWord.append(pwdLetters.randomElement()!)
    }
    return passWord
}

In the above code, we have created a function that will create a random string. Inside the function, we have taken the characters set in the constant with the name pwdLetters. After that, we are using for loop to get pick a random character from the character set we have taken in the constant.

Now let’s see how to use our Swift function to generate a random password.

Usage:

// Generate a password with a length of 8 characters
print( randomPassword(pwdLength: 8) )

It will return a random string something like you can see below:

DkXR(M2Z

Now if we want to create a password of 14 characters, then we just have to pass this length as the input parameter to the function:

randomPassword(pwdLength: 14)

If we print the above code, it will return something like you can see below:

6XnM3NYSmom3c4

 

Well, you can see that the generated password from our function is quite secure and can be used in our project.

I hope, this tutorial will be helpful for you.

Leave a Reply

Your email address will not be published.