我在 Ubuntu 中使用 Swift,收到一条错误消息,指出 arc4random 是一个无法解析的标识符。有关此已知错误的更多信息此处。基本上,该功能仅存在于 BSD 发行版中。我尝试过模块映射头文件、apt-getting 包,但错误越来越多,这不值得追求,因为这个功能并不经常使用。
Linux 中是否有兼容 Swift 的获取带有上限参数的伪随机数的函数?
斯威夫特4.2
let random = Int.random(in: 0...100)
https://developer.apple.com/documentation/swift/int/2995648-random
PS。它可以在 Linux 中运行。
如果在函数内生成随机数,则使用 srandom(UInt32(time(nil)))
在函数内每次都可以生成相同的随机数。 相反,在
main.swift
的顶部准备一次随机种子,然后随机应该在整个过程中表现得如预期。示例:
//
// 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))
如果您将
srandom
调用放入我的
getRandomNum
函数中,Linux 上的 Swift(我的例子是 Ubuntu)每次都会生成相同的数字。注意事项:
srandom
和
random
不会创建“真正的”随机数,并且在制作可能成为黑客目标的关键任务应用程序时可能会成为安全问题。在这种情况下,唯一真正的解决方案是直接通过
/dev/random
执行 Linux 的
Process()
,并使用其结果。但这超出了问题的范围。
#if os(Linux)
srandom(UInt32(time(nil)))
randomString = String(format: "%04d", UInt32(random() % 10000))
#else
randomString = String(format: "%04d", Int(arc4random_uniform(10000)))
#endif
请注意,对 srandom(UInt32(time(nil)))
的调用应该在函数/循环之外,否则它将一遍又一遍地产生相同的值。
#if os(Linux)
random()
#else
arc4random_uniform()
#endif