How to Generate a 4-digit Random Unique Number Using Swift?

Hello Friends Today, through this tutorial, I will tell you how to generate a 4-digit random unique OTP number using Swift Language Program?

You can generate a 4-digit random Unique OTP (One-Time Password) in Swift using the following code:

func generateOTP() -> String {
let digits = "0123456789"
var otp = ""
for _ in 0..<4 {
let randomIndex = Int(arc4random_uniform(UInt32(digits.count)))
let digit = digits[digits.index(digits.startIndex, offsetBy: randomIndex)]
return otp
let randomOTP = generateOTP()
print("Random 4-digit OTP: \(randomOTP)")

This code defines a function `generateOTP` that generates a 4-digit OTP using digits from 0 to 9. It uses `arc4random_uniform` to generate random indices and then selects the corresponding digits to form the OTP. Finally, it prints the generated OTP.