Hello Friends Today, through this tutorial, I will tell you how to generate a 6 digit Unique random number in Swift?
Here are two ways to generate a 6-digit random number in Swift:
Using `arc4random_uniform` and string manipulation:-
func generateSixDigitNumber() -> String { // Generate a random integer between 100000 and 999999 (inclusive) let randomNumber = Int(arc4random_uniform(900000)) + 100000 // Convert the integer to a string let stringNumber = String(randomNumber) // Ensure the string has 6 digits by prepending leading zeros if necessary let paddedNumber = String(format: "%06d", randomNumber) return paddedNumber } // Example usage let number = generateSixDigitNumber() print("Generated 6-digit number: \(number)")
Explanation:-
1. The `generateSixDigitNumber` function uses `arc4random_uniform` to generate a random integer between 0 (inclusive) and the provided upper bound (exclusive). We set the upper bound to 900000 to ensure the range falls within numbers less than 1 million.
2. It adds 100000 to the random number to guarantee it lies within the desired range (100000 to 999999).
3. It converts the integer to a string using `String(randomNumber)`.
4. It uses `String(format: “%06d”, randomNumber)` to format the string by padding it with leading zeros if necessary to reach a length of 6.
5. Finally, it returns the padded string representing the 6-digit number.