【问题标题】:swift: how to remove randomly from 1 to 3 items?swift:如何从 1 到 3 个项目中随机删除?
【发布时间】:2015-08-05 14:07:03
【问题描述】:

我的代码仅随机移除一枚硬币。如何随机取出 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")
        }
    }
}

【问题讨论】:

标签: swift random hidden arc4random


【解决方案1】:

对于随机我推荐这个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)

【讨论】:

  • 这很好,恭喜。但我觉得应该是if range.startIndex &lt; 0 {
【解决方案2】:

试试这个

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")
}

【讨论】:

    猜你喜欢
    • 2021-06-17
    • 1970-01-01
    • 2011-06-16
    • 1970-01-01
    • 2016-12-12
    • 2017-12-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多