Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,845 questions

51,766 answers

573 users

How to assign a random number using a cryptographically secure random number generator in Swift

1 Answer

0 votes
import Foundation
import Security

/// Generates a cryptographically secure random number within a given range.
func secureRandomNumber(in range: ClosedRange<Int>) -> Int? {
    // Ensure the range is valid
    guard range.lowerBound < range.upperBound else {
        print("Invalid range: \(range)")
        return nil
    }
    
    // Calculate the range size
    let rangeSize = range.upperBound - range.lowerBound + 1
    
    // Determine the number of bytes needed to represent the range
    let byteCount = MemoryLayout<UInt32>.size
    var randomBytes = [UInt8](repeating: 0, count: byteCount)
    
    // Generate random bytes
    let result = SecRandomCopyBytes(kSecRandomDefault, byteCount, &randomBytes)
    if result != errSecSuccess {
        print("Failed to generate random bytes: \(result)")
        return nil
    }
    
    // Convert the bytes to a UInt32
    let randomValue = randomBytes.withUnsafeBytes { pointer -> UInt32 in
        return pointer.load(as: UInt32.self)
    }
    
    // Map the random value to the desired range
    let randomInRange = Int(randomValue % UInt32(rangeSize)) + range.lowerBound
    return randomInRange
}

if let randomNumber = secureRandomNumber(in: 1...100) {
    print("Secure random number: \(randomNumber)")
} else {
    print("Failed to generate a secure random number.")
}



/*
run:

Secure random number: 14

*/

 



answered Aug 21, 2025 by avibootz
...