使用Swift生成随机数 [英] Generating random numbers with Swift

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

问题描述

我需要生成一个随机数。

I need to generate a random number.

看来 arc4random 函数不再存在,而 arc4random_uniform 函数。

It appears the arc4random function no longer exists as well as the arc4random_uniform function.

我拥有的选项是 arc4random_stir() arc4random_buf(UnsafeMutablePointer< Void> ;、 Int) arc4random_addrandom(UnsafeMutablePointer< UInt8>,Int32)

The options I have are arc4random_stir(), arc4random_buf(UnsafeMutablePointer<Void>, Int), and arc4random_addrandom(UnsafeMutablePointer<UInt8>, Int32).

我在函数上找不到任何文档,头文件中也没有注释。

I can't find any docs on the functions and no comments in the header files give hints.

推荐答案

===== Swift 4.2 / Xcode 10 =====

let randomIntFrom0To10 = Int.random(in: 1..<10)
let randomFloat = Float.random(in: 0..<1)

// if you want to get a random element in an array
let greetings = ["hey", "hi", "hello", "hola"]
greetings.randomElement()

在后台,Swift使用 arc4random_buf 来完成工作。

Under the hood Swift uses arc4random_buf to get job done.

===== Swift 4.1 / Xcode 9 =====

arc4random()返回一个随机数,范围为 0 4294967295

arc4random() returns a random number in the range of 0 to 4 294 967 295

drand48()返回一个随机数,范围为 0.0 1.0

drand48() returns a random number in the range of 0.0 to 1.0

arc4random_uniform(N)返回随机数,范围为 0 N-1

arc4random_uniform(N) returns a random number in the range of 0 to N - 1

示例:

arc4random() // => UInt32 = 2739058784
arc4random() // => UInt32 = 2672503239
arc4random() // => UInt32 = 3990537167
arc4random() // => UInt32 = 2516511476
arc4random() // => UInt32 = 3959558840

drand48() // => Double = 0.88642843322303122
drand48() // => Double = 0.015582849408328769
drand48() // => Double = 0.58409022031727176
drand48() // => Double = 0.15936862653180484
drand48() // => Double = 0.38371587480719427

arc4random_uniform(3) // => UInt32 = 0
arc4random_uniform(3) // => UInt32 = 1
arc4random_uniform(3) // => UInt32 = 0
arc4random_uniform(3) // => UInt32 = 1
arc4random_uniform(3) // => UInt32 = 2

arc4random_uniform()推荐用于 arc4random()%upper_bound ,因为当上限不是2的幂时,它避免了模偏差。

arc4random_uniform() is recommended over constructions like arc4random() % upper_bound as it avoids "modulo bias" when the upper bound is not a power of two.

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

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