Search code examples
arraysswiftloopsforeachexcept

create a all but one item loop to apply effects


I would like my swift code to make a kind of loop that all items follow except one stated by the user. So for example below, I listed 4 buttons and 1 objc functions linked with the buttons. In b1 hit I know I can just write

b1.backgroundcolor = blue and b2.backgroundcolor = green, b3.backgroundcolor = green. Butt I wanted to see if I could do something like [b1!,b2,b3].forEach{$0.backgroundcolor = .green.}

import UIKit

class ViewController: UIViewController {

var b1 = UIButton()
var b2 = UIButton()
var b3 = UIButton()

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view.

    [b1,b3,b2].forEach{
        $0.translatesAutoresizingMaskIntoConstraints = false
        view.addSubview($0)
        $0.backgroundColor = .blue
    }


    b1.addTarget(self, action: #selector(b1Hit), for: .touchUpInside)

}

@objc func b1Hit(){

    change all buttons background color to green except b1

}

}

Solution

  • Option 1: Use for in with where clause

    Use a for in loop with a where clause to exclude the one you want to exclude:

    // change all buttons background color to green except b1
    for button in [b1, b2, b3] where button != b1 {
        button.backgroundColor = .green
    }
    

    Option 2: Use Set and subtracting

    Set([b1, b2, b3]).subtracting([b1]).forEach {
        $0.backgroundColor = .green
    }
    

    or

    for button in Set([b1, b2, b3]).subtracting([b1]) {
        button.backgroundColor = .green
    }