如何在Apple的Swift语言中生成一个随机数?

论坛 期权论坛 编程之家     
选择匿名的用户   2021-5-23 15:36   53   0

本文翻译自:How does one generate a random number in Apple's Swift language?

I realize the Swift book provided an implementation of a random number generator. 我意识到Swift书提供了随机数生成器的实现。 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? 或者是否有一个我们现在可以使用的库?


#1楼

参考:https://stackoom.com/question/1cjLl/如何在Apple的Swift语言中生成一个随机数


#2楼

I've been able to just use rand() to get a random CInt. 我已经能够使用rand()来获得一个随机的CInt。 You can make it an Int by using something like this: 您可以使用以下内容将其设为Int:

let myVar: Int = Int(rand())

You can use your favourite C random function, and just convert to value to Int if needed. 您可以使用自己喜欢的C随机函数,如果需要,只需将值转换为Int即可。


#3楼

You can do it the same way that you would in C: 你可以像在C中那样做:

let randomNumber = arc4random()

randomNumber is inferred to be of type UInt32 (a 32-bit unsigned integer) randomNumber被推断为类型为UInt32 (32位无符号整数)


#4楼

Swift 4.2+ Swift 4.2+

Swift 4.2 shipped with Xcode 10 introduces new easy-to-use random functions for many data types. 随Xcode 10一起提供的Swift 4.2为许多数据类型引入了易于使用的新随机函数。 You can call the random() method on numeric types. 您可以在数字类型上调用random()方法。

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

#5楼

Use arc4random_uniform(n) for a random integer between 0 and n-1. 使用arc4random_uniform(n)表示0到n-1之间的随机整数。

let diceRoll = Int(arc4random_uniform(6) + 1)

Cast the result to Int so you don't have to explicitly type your vars as UInt32 (which seems un-Swifty). 将结果转换为Int,因此您不必将您的变量显式键入为UInt32 (这似乎是非Swifty)。


#6楼

Edit for Swift 4.2 编辑Swift 4.2

Starting in Swift 4.2, instead of using the imported C function arc4random_uniform(), you can now use Swift's own native functions. 从Swift 4.2开始,您现在可以使用Swift自己的本机函数,而不是使用导入的C函数arc4random_uniform()。

// Generates integers starting with 0 up to, and including, 10
Int.random(in: 0 ... 10)

You can use random(in:) to get random values for other primitive values as well; 您可以使用random(in:)来获取其他原始值的随机值; such as Int, Double, Float and even Bool. 比如Int,Double,Float甚至Bool。

Swift versions < 4.2 Swift版本<4.2

This method will generate a random Int value between the given minimum and maximum 此方法将在给定的最小值和最大值之间生成随机Int

func randomInt(min: Int, max: Int) -> Int {
    return min + Int(arc4random_uniform(UInt32(max - min + 1)))
}
分享到 :
0 人收藏
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

积分:3875789
帖子:775174
精华:0
期权论坛 期权论坛
发布
内容

下载期权论坛手机APP