Apple 的 Swift 语言如何生成一个随机数? [英] How does one generate a random number in Apple's Swift language?

查看:31
本文介绍了Apple 的 Swift 语言如何生成一个随机数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我意识到 Swift 书提供了一个随机数生成器的实现.将此实现复制并粘贴到自己的程序中是最佳实践吗?或者有没有我们现在可以使用的库可以做到这一点?

I realize the Swift book provided an implementation of a random number generator. Is the best practice to copy and paste this implementation in one's own program? Or is there a library that does this that we can use now?

推荐答案

Swift 4.2+

Xcode 10 附带的 Swift 4.2 为许多数据类型引入了新的易于使用的随机函数.您可以对数字类型调用 random() 方法.

Swift 4.2 shipped with Xcode 10 introduces new easy-to-use random functions for many data types. You can call the random() method on numeric types.

let randomInt = Int.random(in: 0..<6)
let randomDouble = Double.random(in: 2.71828...3.14159)
let randomBool = Bool.random()

这篇关于Apple 的 Swift 语言如何生成一个随机数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆