Search code examples
arraysswiftnsbutton

How to perform functions with multiple NSButtons in an array?


I currently have 18 check-type switches as NSButtons in Swift. What I am trying to do is get them all to NSOnState. Instead of doing

switch1.state = NSOnState

each time, I want to do something along the lines of this:

let Switches: [NSButton] = [Switch1, Switch2, Switch3, Switch4, Switch5, Switch6, Switch7, Switch8, Switch9, Switch10, Switch11, Switch12, Switch13, Switch14, Switch15, Switch16, Switch17, Switch18]
Switches[0-17].state = NSOnState

The issue with this is that I don't know how to perform the second line properly. It is showing he the error: "Thread 1: EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode=0x0)

Any solutions or suggestions will help, thanks!

(Please note I don't know Objective-C, only Swift)


Solution

  • forEach is what you are looking for

    switches.forEach{ $0.state = NSOnState } 
    

    By the way: Variable names are supposed to start with a lowercase letter.