How to generate an 8 digits random number in Swift

1 Answer

0 votes
import Foundation

/// Namespace for cryptographically secure 8-digit number and code utilities.
public enum RandomCodeGenerator {
    
    // Numeric constants with underscore separators for visual clarity
    private static let min8DigitInt: Int = 10_000_000
    private static let max8DigitInt: Int = 99_999_999
    private static let maxCodeValue: Int = 99_999_999
    
    /// Generates a cryptographically secure 8-digit positive integer between 10,000,000 and 99,999,999 (inclusive).
    /// Guaranteed to start with a non-zero digit (1–9).
    ///
    /// - Returns: An 8-digit `Int`.
    public static func generate8DigitNumber() -> Int {
        // Swift's native Int.random(in:) accepts ClosedRange (a...b) natively
        // and uses the system's cryptographically secure PRNG automatically.
        return Int.random(in: min8DigitInt...max8DigitInt)
    }
    
    /// Generates an 8-character numeric string code between "00000000" and "99999999".
    /// Preserves leading zeros using String format specifiers, making it suitable for OTPs, PINs, or tokens.
    ///
    /// - Returns: An 8-character numeric `String` padded with leading zeros if necessary.
    public static func generate8DigitCode() -> String {
        let rawValue = Int.random(in: 0...maxCodeValue)
        
        // String(format: "%08d", ...) formats the integer with a minimum width of 8,
        // padding shorter values with leading zeros.
        return String(format: "%08d", rawValue)
    }
}

// ==========================================
// Example Execution
// ==========================================

func main() {
    print("=== Generating 8-Digit Integers [10000000 to 99999999] ===")
    for index in 1...3 {
        let randomNumber = RandomCodeGenerator.generate8DigitNumber()
        print("Generated integer #\(index): \(randomNumber)")
    }
    
    print("\n=== Generating 8-Digit String Codes [00000000 to 99999999] ===")
    for index in 1...3 {
        let randomCode = RandomCodeGenerator.generate8DigitCode()
        print("Generated OTP code #\(index): \(randomCode)")
    }
}

// Execute program main
main()


/*
run:

=== Generating 8-Digit Integers [10000000 to 99999999] ===
Generated integer #1: 27803289
Generated integer #2: 64060177
Generated integer #3: 13393335

=== Generating 8-Digit String Codes [00000000 to 99999999] ===
Generated OTP code #1: 50315579
Generated OTP code #2: 19819077
Generated OTP code #3: 15774851

*/

 



answered Oct 3 by avibootz
...