Swift program to generate a password


A password is a combination of various characters of a specified length and is used to authenticate or gain access to the system or login to an account. It is designed for security purposes and ensures that only an authorized user can access or log in to the specific account. It is important to select a strong password so that other people cannot crack it. It is generated according to the following conditions −

  • Contains at least one uppercase letter.

  • Contains at least one lowercase letter.

  • Contains at least one number.

  • Length must be 8 characters

  • Contains at least one special character.

In Swift, we can generate a random password with the help of the following methods −

  • Using random() method

  • Using randomElement() method

Method 1: Using random() method

As we know that s password is a set of characters or s unique string so to create a random password we use the random() method. This method is used to create a random string of the specified range.

Syntax

func random(in: Range)

Here, the random function takes only one parameter that is range. It represents the range in which the random value is created. Its value must not be empty.

Algorithm

  • Step 1 − Create a function which takes password length as input.

  • Step 2 − This function creates three variables to store: uppercase and lowercase letters, numbers and special characters.

  • Step 3 − Combine all the three variables to create a single string.

  • Step 4 − Create an empty string to store the new password.

  • Step 5 − Run a for-in loop to iterate through the given length and randomly select characters from the given set of characters.

  • Step 6 − Append the randomly selected characters in the new string.

  • Step 7 − Return the final password.

  • Step 8 − Create a variable to store the length of the password.

  • Step 9 − Call the function and pass the length into the string.

  • Step 10 − Display the output.

Example

In the following Swift program, we will generate a random password. So for that, we will define a function which takes the length of the password as input and return the random password of the desired size. This function uses uppercase, lowercase, numbers and special characters to generate a password. It uses Int.random(in:0..<allChars.count) function to generate a random index according to the given range and then uses the generated index to get the character from the specified string and then append then into a new string to get the random password.

import Foundation
import Glibc

func createRandomPassword(size: Int) -> String 
{
    let chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
    let nums = "0123456789"
    let specialChars = "!@$%#^(&)*_-+~=`|[{]}/:;<>,.?/"
    
    let allChars = chars + nums + specialChars 
    var newPassword = ""
    
    for _ in 0..<size {
        let randomIndexValue = Int.random(in: 0..<allChars.count)
        let character = Array(allChars)[randomIndexValue]
        newPassword.append(character)
    }
    return newPassword 
}

let length = 10
let createdPassword = createRandomPassword(size: length)
print("New Password is:", createdPassword)

Output

New Password is: ui(Kw <BgV+

Method 2: Using randomElement() method

To create a random password we use the randomElement() method. This method returns a random element from the given sequence or collection.

Syntax

func randomElement()

It returns random elements. If the given collection is empty, then it will return nil.

Algorithm

  • Step 1 − Create a function which takes password length as input.

  • Step 2 − This function first checks if the input length of the password is valid or not(that is greater than 8 or not). If no return empty string.

  • Step 3 − If yes, then this function has a set of multiple characters like uppercase and lowercase letters, numbers and special characters in the string.

  • Step 4 − Extract random characters from the given string till the desired length of the password.

  • Step 5 − Return the new password.

  • Step 6 − Create a variable to store the length of the password.

  • Step 7 − Call the function and pass the length into the string.

  • Step 8 − Display the output.

Example

In the following Swift program, we will generate a random password. So for that, we will define a function which takes the length of the password as input and return the random password of the desired size. Then this function generates the random password by choosing characters from the given set of characters which includes uppercase, lowercase, numbers and special characters with the help of String((0..<size).map{ _ in pwdChars.randomElement()! }) method. And finally display the output.

import Foundation
import Glibc

func createRandomPassword(size: Int) -> String{
   if (size < 8){
      return ""
   }
   let pwdChars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$%^&*()_-+=<>?"
   let newPassword = String((0..<size).map{ _ in pwdChars.randomElement()! })
   return newPassword
}

let passwordLen = 8
let newPassword = createRandomPassword(size: passwordLen)
 
if newPassword == ""
{
   print("Invalid length of the Password! Try Again")
}
else{
   print("New Password is:", newPassword) 
}

Output

New Password is: luCia+@a

Conclusion

So this is how we can generate a password. Password is just like a key to your lock on certain accounts. It is also useful for network security, file encryption, application authentications, etc. It should be unique for each account, also kept secret and not shared with other people.

Updated on: 15-Jun-2023

255 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements