Swift arc4random_uniform (max) on Linux

I work with Swift in Ubuntu and I get an error that arc4random is an unresolved identifier. Read more about this known bug here . In principle, a function exists only in BSD distributions. I tried module header files, apt-receiving packages, and I get more and more errors, which should not be done, since this function is not used very often.

Are there any functions for getting pseudo-random numbers with an upper bound parameter compatible with Swift on Linux?

+6
source share
3 answers

I went with something similar for 4 digit random numbers:

#if os(Linux) srandom(UInt32(time(nil))) randomString = String(format: "%04d", UInt32(random() % 10000)) #else randomString = String(format: "%04d", Int(arc4random_uniform(10000))) #endif 

Edit: Note that the srandom(UInt32(time(nil))) call srandom(UInt32(time(nil))) must be outside the / loop function, otherwise it will call the same value again and again

+3
source

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.

+3
source

Could you try something like this?

  #if os(Linux) random() #else arc4random_uniform() #endif 
+1
source

Source: https://habr.com/ru/post/1012991/


All Articles