我在Ubuntu中使用Swift,我收到一个错误,arc4random是一个未解析的标识符。有关此已知错误的更多信息here。基本上,该功能仅存在于BSD发行版中。我已经尝试了模块映射头文件,apt-getting软件包,并且我得到越来越多的错误,这是不值得追求的,因为这个函数不经常使用。
是否有任何函数可以获取具有与Linux中的Swift兼容的上限参数的伪随机数?
答案 0 :(得分:6)
Swift 4.2
let random = Int.random(in: 0...100)
https://developer.apple.com/documentation/swift/int/2995648-random
PS。它可以在Linux中使用。
答案 1 :(得分:5)
我选择了4位数的随机数:
#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)))
的调用应该在函数/循环之外,否则它将反复生成相同的值
答案 2 :(得分:5)
如果在函数中生成随机数,则在函数中使用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()
,并使用其结果。但这超出了问题的范围。
答案 3 :(得分:2)
你可以试试这样的东西吗?
['a', 'a', 'word', 'word', 'if', 'as']