swift: 如何随机删除1到3个项目?
swift: how to remove randomly from 1 to 3 items?
我的代码只随机删除一枚硬币。我如何从 1 到 3 个硬币中随机取出?
@IBAction func endTurn(sender: UIButton!) {
if coins.count > 0 { // @IBOutlet var coins: [UIButton]! (21 coins)
let index: Int = Int(arc4random_uniform(UInt32(coins.count)))
coins[index].hidden = true
self.coins.removeAtIndex(index)
if coins.isEmpty {
println("GameOver")
}
}
}
试试这个
let numberToDelete = Int(arc4random_uniform(UInt32(3))) + 1
for i in 0..<numberToDelete{
let indexToDelete = Int(arc4random_uniform(UInt32(coins.count)))
coins.removeAtIndex(indexToDelete)
if coins.isEmpty{
break;
}
}
if coins.isEmpty{
println("GameOver")
}
对于随机数,我推荐这个 extension
:
extension Int {
static func random(range: Range<Int> ) -> Int {
var offset = 0
if range.startIndex < 0 {
offset = abs(range.startIndex)
}
let min = UInt32(range.startIndex + offset)
let max = UInt32(range.endIndex + offset)
return Int(min + arc4random_uniform(max - min)) - offset
}
}
然后:
var i = Int.random(1...5)
我的代码只随机删除一枚硬币。我如何从 1 到 3 个硬币中随机取出?
@IBAction func endTurn(sender: UIButton!) {
if coins.count > 0 { // @IBOutlet var coins: [UIButton]! (21 coins)
let index: Int = Int(arc4random_uniform(UInt32(coins.count)))
coins[index].hidden = true
self.coins.removeAtIndex(index)
if coins.isEmpty {
println("GameOver")
}
}
}
试试这个
let numberToDelete = Int(arc4random_uniform(UInt32(3))) + 1
for i in 0..<numberToDelete{
let indexToDelete = Int(arc4random_uniform(UInt32(coins.count)))
coins.removeAtIndex(indexToDelete)
if coins.isEmpty{
break;
}
}
if coins.isEmpty{
println("GameOver")
}
对于随机数,我推荐这个 extension
:
extension Int {
static func random(range: Range<Int> ) -> Int {
var offset = 0
if range.startIndex < 0 {
offset = abs(range.startIndex)
}
let min = UInt32(range.startIndex + offset)
let max = UInt32(range.endIndex + offset)
return Int(min + arc4random_uniform(max - min)) - offset
}
}
然后:
var i = Int.random(1...5)