If you generate a random number inside a function using srandom(UInt32(time(nil))) inside a function , it can produce the same random number each time.
Instead, prepare a random seed at the top of your main.swift once, and then the random behavior should behave as expected.
Example:
// // main.swift // Top of your code // import Foundation #if os(Linux) srandom(UInt32(time(nil))) #endif func getRandomNum(_ min: Int, _ max: Int) -> Int { #if os(Linux) return Int(random() % max) + min #else return Int(arc4random_uniform(UInt32(max)) + UInt32(min)) #endif } // Print random numbers between 1 and 10 print(getRandomNum(1, 10)) print(getRandomNum(1, 10)) print(getRandomNum(1, 10)) print(getRandomNum(1, 10)) print(getRandomNum(1, 10))
Swift on Linux (Ubuntu in my case) will call the same number every time you put a srandom call inside my getRandomNum function.
Note:
srandom and random do not create a "truly" random number and can be a security issue when creating mission-critical applications that would be hacked. The only real solution in this case is to run Linux /dev/random directly through Process() and use its result. But this is beyond the scope of the question.
source share