抢红包算法@随机算法

生成随机数
// Swift 4.2
/ 1  
let digit = Int.random(in: 0..<10)
​
// 2
if let anotherDigit = (0..<10).randomElement() {
 print(anotherDigit)
} else {
 print("Empty range.")
}
​
// 3
let double = Double.random(in: 0..<1)
let float = Float.random(in: 0..<1)
let cgFloat = CGFloat.random(in: 0..<1)
let bool = Bool.random()

注:randomElement() 如果 range 是空,返回 nil

数组随机
if let song = playlist.randomElement() {
 print(song)
} else {
 print("Empty playlist.")
}
洗牌算法
let shuffledPlaylist = playlist.shuffled()
names.shuffle()

Swift 4.2 更新指北(译)

你可能感兴趣的:(抢红包算法@随机算法)