Swift arc4random_uniform(max) in Linux

后端 未结 4 1018
猫巷女王i
猫巷女王i 2021-02-14 00:06

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 e

4条回答
  •  长发绾君心
    2021-02-14 00:33

    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.

提交回复
热议问题