linux - Swift Linux 生成随机 bool

标签 linux swift server-side-swift

我正在尝试对 Bool 进行静态扩展,以便在调用时返回随机的 true/false 值。我正在努力使这项工作:

static func coinFlip() -> Bool {
    #if os(Linux)
    srand(UInt32(time(nil)))
    let result = Int(random() % 2)
    if result == 0 {
        return false
    } else {
        return true
    }
    #else
    return arc4random_uniform(2) == 0
    #endif
}

我在服务器端 Swift 应用程序中调用的路由范围内使用它。每当它第一次被调用时,它都会返回一个随机值,但在同一范围内对该函数的所有后续调用都不会随机化输出。例如:

for _ in 1...5 {
    let coin = Bool.coinFlip()
    if coin == true {
        print("coin flip true")
    } else {
        print("coin flip false")
    }
}

...产生这样的输出:

coin flip false
coin flip false
coin flip false
coin flip false
coin flip false

...但是如果我再次单独调用路由,我会得到:

coin flip true
coin flip true
coin flip true
coin flip true
coin flip true

srand(UInt32(time(nil))) 只随机化 random() 的伪随机序列是否有问题?我不知道该怎么办。预先感谢您的帮助!

最佳答案

time(nil))秒数的形式返回当前时间, 这意味着 你用相同的值为随机数生成器播种 该方法在一秒间隔内被多次调用。

你应该只在申请时调用一次srand(UInt32(time(nil))) 启动,而不是在每次调用 coinFlip() 时。

另外,函数可以简化一点,我会调用 它是 random(),而不是 coinFlip():

#if os(Linux)
    srand(UInt32(time(nil)))
#endif

extension Bool {
    static func random() -> Bool {
        #if os(Linux)
            return Glibc.random() % 2 == 0
        #else
            return arc4random_uniform(2) == 0
        #endif
    }
}

for _ in 1...5 {
    print(Bool.random())
}

关于linux - Swift Linux 生成随机 bool ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42737124/

相关文章:

swift - Swift 可执行二进制文件是否需要 .swiftmodule、.swiftdoc 和 .build 文件才能运行?

swift - 数据库不存在 - 使用 Vapor 3 和 Fluent 的服务器端 Swift 中的 PostgreSQL

swift - Perfect如何获取服务端文件上传进度

linux - Quartus 13.1 安装程序出现段错误(核心已转储)

php - WordPress 网站或服务器因上传大量 php 和 html 文件而遭到黑客攻击

linux - php 脚本刚刚用垃圾填满了硬盘驱动器我如何找到它?

ios - 我没有显示图像、启动屏幕、应用程序图标等,关于为什么的任何想法?

ios - DYLD,没有名称的缓存图像(@rpath/libswiftCore.dylib)

linux - 切换到Secure world后OP-TEE的Linux调度器如何工作

ios - 从使用 MessageKit 创建的 ChatViewController 推送其他 ViewController