swift之随机数

Posted ybw123321

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了swift之随机数相关的知识,希望对你有一定的参考价值。

开发中很多地方都会用到随机数,下面说说随机数的使用。

先来个小示例

let dicFaceCount: UInt32 = 16 //定义随机数产生范围
let randomRoll = Int(arc4random_uniform(dicFaceCount)) + 1 //用arc4random方法生成随机数
print(randomRoll)

 更多时候我们把它写成一个函数方便调用

func randomInRange(range: Range<Int>) -> Int {
       let count = UInt32(range.endIndex - range.startIndex) //定义随机数产生范围,endIndex为upper bounds,startIndex为low bounds
       retrun Int(arc4random_uniform(count)) + range.startIndex //返回一个Int类型的随机数
}

 下面来调用它

for _ in 0...9 {
     print(randomInRange(1...6))  
}

 

以上是关于swift之随机数的主要内容,如果未能解决你的问题,请参考以下文章