Generate random Password in Swift

In this Swift tutorial, you will learn how to generate a random password in Swift programming.

For generating a random password string, here I am going to create a function with only a few lines of statements in it. Every time you run the function, it will generate a random password.

So let’s continue…

If you don’t have any idea of functions, then read the tutorial on functions in Swift with examples.

Swift function to generate random password

Below is the code to create the function:

func randomPassword(pwdLength: Int) -> String {
    let charactersSet = "[email protected]#$%&()0123456789"
    var thePassword = ""
    for _ in 0 ..< pwdLength {
    return thePassword

In the above code, we are defining a function that is taking an integer type parameter which will be the length of the password that will be generated. The return type we set is a string.

Inside the function statements, we have taken the set of characters as a string formatted. It is “[email protected]#$%&()0123456789“. The generated password will be consisted of choosing characters from this characters set.


To use the function we just created is quite easy to use. All you need is just to call it:

randomPassword(pwdLength: 12)

During calling the function, you can see that we have set the password length to 12. You can test it by printing it in the console:

print( randomPassword(pwdLength: 12) )

To generate a random 8 characters password, we have to call the function in the same manner. The only difference is that we have to pass 8 as an input parameter:

randomPassword(pwdLength: 8)

It will generate a password that will be 8 characters long.

Why do we create a function to generate a random password?

Well, if we code in Swift directly instead of creating a function, then it will work as same as it is working by creating a function.

Then why do we create a function for this task if it was possible without it.

Well, I have already mentioned in this tutorial – Functions in Swift with examples, that code inside functions are reusable. We don’t have to write one code again and again. It will save a lot of time.

By creating a function for our task we don’t have to write the Swift code again to generate the password if we have to do this task multiple times.

Whenever we need to generate a random password, all we need is just call the function.