用Swift生成随机数

前端之家收集整理的这篇文章主要介绍了用Swift生成随机数前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我需要生成一个随机数。

它看起来arc4random函数不再存在以及arc4random_uniform函数

我具有的选项是arc4random_stir(),arc4random_buf(UnsafeMutablePointer< Void>,Int)和arc4random_addrandom(UnsafeMutablePointer< UInt8>,Int32)。

我找不到任何文档的功能,没有在头文件中的注释提示

arc4random()

Returns a random number in the range of 0 to 2^32.

Good to know: If you do not a number of that super large range then
you can also use the functions rand() and random() which return a
random number from “just” half the range.

drand48()

Returns a random double between 0.0 and 1.0

Be aware that the return value is Double and not Int! To learn more
about drand48() and its “family” of similar functions check the 07000

arc4random_uniform(UInt32)

Returns a random number between 0 and the inserted parameter minus 1.

For example arc4random_uniform(3) may return 0,1 or 2 but not 3.

That function is the most common random function but it has one minor
issue: dealing with UInt32 in Swift is not very common so a conversion
to Int is normally done like in the following example:

let random = Int(arc4random_uniform(3))

那么为什么要arc4random()和arc4random_uniform呢?除了缩小范围之外,均匀性还考虑了在将十进制数转换为二进制时产生的模偏差。模运算符使一些数字更频繁地出现。

原文链接:https://www.f2er.com/swift/321397.html

猜你在找的Swift相关文章