swift - 在 Swift 中使用 srand(time(NULL)) 会产生编译器错误

标签 swift

我正在尝试使用 srand(time(NULL)) 在 Swift 中为随机数生成器播种,但出现此编译器错误:

Use of unresolved identifier 'NULL'

还有其他方法可以使用 srand() 吗?

最佳答案

Swift 使用 nil 作为 NULL 指针,time() 的返回值必须为 转换为 UInt32:

srand(UInt32(time(nil)))

但请考虑改用 arc4random() 或其变体。来自 http://nshipster.com/random/ :

  • arc4random does not require an initial seed (with srand or srandom), making it that much easier to use.
  • arc4random has a range up to 0x100000000 (4294967296), whereas rand and random top out at RAND_MAX = 0x7fffffff (2147483647).
  • rand has often been implemented in a way that regularly cycles low bits, making it more predictable.

例如,

let x = arc4random_uniform(10)

生成 0 ... 9 范围内的随机数。

关于swift - 在 Swift 中使用 srand(time(NULL)) 会产生编译器错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25610857/

相关文章:

ios - Swift - 使用 alamofire 发布请求

ios - Swift - 数组过滤器不删除对象

ios - 如何使用 Swift 4.2 在 TableView 中创建 JSON 可编码结构数据的搜索功能?

swift - 远程数据不会显示在 tableView 上

ios - 项目中的颜色代码未正确执行

swift - 从同一类中的结构调用方法

ios - 在自定义框架中访问应用程序的捆绑标识符

带有 UISegmentedControl 的 Swift UiTableView 不刷新行

swift - 使用 Firebase 和 Swift 3 进行一对多查询

ios - 用户先前注销后使用无效数据错误地登录