Swift 4.2后产生随机数
2年前 • 1055次点击 • 来自 移动端
标签: Swift
Swift 4.2后产生随机数使用random可简化大量的工作,是时候扔掉难用的arc4randomuniform:
例1:随机生成 1 - 10 中的一个Int
let number = Int.random(in: 1...10)
例2:随机生成 0.0 - 1.0 内的一个Float
let fraction = Float.random(in: 0..<1)
例3:随机生成一个Bool
let yesOrNo = Bool.random()
例4:从array中随机挑选一个对象
let cars = ["Benz", "BMW", "Porche"]
let carChoosed = cars.randomElement()
例5: 随机打乱
let sequence = 0 ..< 3
let shuffledSequence = sequence.shuffled()
// `shuffledSequence` 生成一个新的array : [0, 2, 3, 1]