Swift program to generate an OTP


An OTP is known as a one-time password. It is an automatically generated random numeric string which is used for a single login session or transaction on digital devices. It is generally used to enhance security by providing extra authentication. For example, “423193”, “489201’, etc. To generate OTP Swift provides the following methods −

  • Using random() method

  • Using randomElement() method

Method 1: Using random() method

As we know that OTP is a randomly generated string. So to generate a random string Swift provide an inbuilt function named as random(). It 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 generates OTP.

  • Step 2 − Inside the function, we create a string of numbers 0-9.

  • Step 3 − Specify the length of the OTP.

  • Step 4 − Create an empty string to store OTP.

  • 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 OTP.

  • Step 8 − Call the function to generate OTP.

  • Step 9 − Display the output.

Example

In the following Swift program, we will generate an OTP. So for that, we define a function which returns an OTP. This function creates a string which contains numbers from 0-9 and sets the length of the OTP to 6. Then it iterates through the given length and randomly selects characters from the given set of characters using the Int.random() function and appends each randomly selected character to the new string one by one till the desired length. And finally, return the new OTP.

import Foundation
import Glibc

func createOTP() -> String {
   let numbers = "0123456789"
   let size = 6
   var resOTP = ""

   for _ in 0..<size {
      let randomIndexValue = Int.random(in: 0..<numbers.count)
      let numChar = numbers[numbers.index(numbers.startIndex, offsetBy: randomIndexValue)]
      resOTP.append(numChar)
   }
   return resOTP
}

let finalOTP = createOTP()
print("New generated OTP is:", finalOTP)

Output

New generated OTP is: 311579

Method 2: Using randomElement() method

Swift provides an inbuilt function named as randomElement() method using this function we can generate OTP randomly because this function 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 generates OTP.

  • Step 2 − Inside the function, we create a string of numbers 0-9.

  • Step 3 − Specify the length of the OTP.

  • Step 4 − Select the random characters from the string using the randomElement() function an map them into an array using the compactMap() function.

  • Step 5 − Return the OTP by converting the array into a string.

  • Step 6 − Call the function to generate OTP.

  • Step 7 − Display the output.

Example

In the following Swift program, we will generate an OTP. So for that, we define a function which returns an OTP. This function creates a string which contains numbers from 0-9 and sets the length of the OTP to 6. Then it iterates through the given length and randomly selects characters from the given set of characters using the randomElement() function and maps them into an array one by one till the desired length using compactMap() method. And finally, return the new OTP by converting the array into a string using the String() initializer.

import Foundation
import Glibc

func createOTP() -> String {
   let numbers = "0123456789"
   let otpLen = 6
   let newOTP = (0..<otpLen).compactMap { _ in numbers.randomElement() }
    
   return String(newOTP)
}

let newOTP = createOTP()
print("New OTP is: \(newOTP)")

Output

New OTP is: 545351

Conclusion

So this is how we can generate OTP. OTP is generally used for authentication and verification, for example, two-factor authentication, account verification, transaction authorization, password reset, etc. It is worked on a time-based algorithm and generates a unique password for each authentication session. It does not use multiple times for the same authentication session and it is valid only for the specified time for that certain login or transaction.

Updated on: 15-Jun-2023

241 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements