Search code examples
swiftrandomhiddenarc4random

swift: how to remove randomly from 1 to 3 items?


My code remove randomly only one coin. How i can remove randomly from 1 to 3 coins?

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

Solution

  • Try this

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