使数组中的3个随机元素不可见

时间:2018-02-20 16:53:05

标签: ios arrays swift

我在阵列中有5个按钮我想在按下按钮时随机取出其中的三个。所以最后两个按钮是可见的

我试过这样:

 @IBAction func eliminateChoiceClicked(_ sender: Any) {

       let buttons:[UIButton] = [buttonA,buttonB,buttonC,buttonD,buttonE]
       let randomNumber = Int(arc4random_uniform(UInt32(3)))
       buttons[randomNumber].isHidden = !buttons[randomNumber].isHidden

    }

但它需要第一个元素[0,1,2],每次按下时只有一个按钮不可见

2 个答案:

答案 0 :(得分:0)

您目前只选择一个按钮。将其更改为循环以选择3.从阵列中删除所选按钮并使其不可见。最后,让其余按钮可见:

@IBAction func eliminateChoiceClicked(_ sender: Any) {

   var buttons:[UIButton] = [buttonA,buttonB,buttonC,buttonD,buttonE]

   // Select 3 buttons randomly and hide them
   for _ in 1...3 {
       let randomNumber = Int(arc4random_uniform(UInt32(buttons.count)))
       let button = buttons.remove(at: randomNumber)
       button.isHidden = true
   }

   // Make the remaining buttons visible
   for button in buttons {
       button.isHidden = false
   }

}

答案 1 :(得分:0)

我刚刚编写了一个简洁的扩展来从数组中获取随机元素:

extension Array {
    func randomItems(count: Int) -> [Element] {
        guard count <= self.count else { fatalError() }
        var notUsedElements: [Element] = self
        var randomElements: [Element] = []
        while randomElements.count != count {
            randomElements.append(notUsedElements.remove(at: Int(arc4random_uniform(UInt32(notUsedElements.count)))))
        }
        return randomElements
    }
}

使用此功能,您可以通过这种方式实现目标:

@IBAction func eliminateChoiceClicked(_ sender: Any) {

    let buttons:[UIButton] = [buttonA, buttonB, buttonC, buttonD, buttonE]
    // make sure all are visible at the beginning
    buttons.forEach { (button) in
        button.isHidden = false
    }

    // hide random 3:
    buttons.randomItems(count: 3).forEach { (button) in
        button.isHidden = true
    }
}