计算 swift 数组中选定按钮的数量

Counting the amount of selected buttons in a swift array

我有 4 个定制的切换按钮。用户可以 select 多个按钮并切换同一个按钮,但是,必须始终至少有 1 个 selected 按钮。

如果 4 个按钮中有 1 个被 selected,则 selected 按钮无法切换为 deselected。

我正在寻找确定此逻辑的方法。我的想法是简单地统计按钮数组中的selected项,如果只有1个selected,则通过return.

转义

这是我的进度

func toggleButton(button: ToggleButton){
    
    let buttonArray = [btn1, btn2, btn3, btn4]
    for btn in buttonArray{
        // Count the amount of selected buttons in buttonArray
        // if 1, return.
    }
    
    button.isSelected = !button.isSelected
}

有没有办法计算 buttonArray 中 selected 按钮的数量?

也许是一个变量 numberOfSelected 来跟踪所选按钮的数量?如果它等于 1,return:

var numberOfSelected = 0
let buttonArray = [btn1, btn2, btn3, btn4]
for btn in buttonArray {
    if btn.isSelected {
        numberOfSelected += 1
    }
}
if numberOfSelected == 1 { return } /// escape via return

在我的操场上:

struct ToggleButton {
    let isSelected: Bool
}
let btn1 = ToggleButton(isSelected: true)
let btn2 = ToggleButton(isSelected: false)
let btn3 = ToggleButton(isSelected: false)
let btn4 = ToggleButton(isSelected: true)
let buttonArray = [btn1, btn2, btn3, btn4]

我能做到:

let count = buttonArray // 2
    .filter(\.isSelected)
    .map { _ in 1 }
    .reduce(0, +)

或:

let otherCount = buttonArray // 2 
    .filter(\.isSelected)
    .reduce(0) { count, _ in
        count.advanced(by: 1)
    }

但如果您真正想知道是否至少选择了一个按钮,您可以直接做:

let atLeastOneButtonSelected = !buttonArray
    .map(\.isSelected)
    .filter { [=13=] }
    .isEmpty