Swift arc4random_uniform(max) in Linux

纵饮孤独 提交于 2020-01-01 04:34:05

问题


I'm working with Swift in Ubuntu, and I am getting an error that arc4random is an unresolved identifier. More information on this known bug here. Basically, the function only exists in BSD distros. I've tried module mapping header files, apt-getting packages, and I get more and more errors, which is not worth pursuing since this one function is not used very often.

Are there any functions to get pseudo random numbers with an upper-bound parameter that is compatible with Swift in Linux?


回答1:


Swift 4.2

let random = Int.random(in: 0...100)

https://developer.apple.com/documentation/swift/int/2995648-random

PS. It works in Linux.




回答2:


I went with something like this 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 call to srandom(UInt32(time(nil))) should be outside a function/loop, otherwise it will produce the same value over and over again




回答3:


If generating a random number within a function, using srandom(UInt32(time(nil))) inside the function can produce the same random number every time.

Instead, prepare the random seed at the top of your main.swift once, and then random should behave as expected throughout.

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 produce the same number every time if you put the srandom call inside my getRandomNum function.

Note of Caution:

srandom and random do not create a "truly" random number, and can be a security concern when making mission-critical applications that would be a target of a hack. The only real solution in that case is to execute Linux's /dev/random directly via Process(), and using its result. But this is outside the scope of the question.




回答4:


You could try something like this?

    #if os(Linux)
       random()
    #else
        arc4random_uniform()
    #endif


来源:https://stackoverflow.com/questions/41035180/swift-arc4random-uniformmax-in-linux

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!