Swift随机数生成
示例
arc4random_uniform(someNumber:UInt32)->UInt32
这使您可以在范围内的随机整数0来someNumber-1。
的最大值UInt32是4,294,967,295(即2^32-1)。
例子:
硬币翻转
letflip=arc4random_uniform(2)//0或1
骰子卷
letroll=arc4random_uniform(6)+1//1...6
十月的随机日
letday=arc4random_uniform(31)+1//1...31
1990年代为随机年份
letyear=1990+arc4random_uniform(10)
一般形式:
let number = min + arc4random_uniform(max - min + 1)
其中number,max和min是UInt32。
笔记
有轻微的模偏置,arc4random因此arc4random_uniform是首选。
您可以将UInt32值转换为,Int但要注意不要超出范围。