JulienM
JulienM

Reputation: 47

Swift : How to perform actions only if an array matches specific conditions?

So I've encountered this problem (beginner in Swift, so you know) and couldn't find a solution here:

I have an array of buttons, that I associate to an array of bools, let's name it litPad.

Basically for instance if button[i] is highlighted, litPad[i] becomes true (by default I set the whol bool array to false).

What I want to achieve is perform certain actions only if some bools are true :

For instance if litPad[3], litPad[6] & litPad[12] are true I'll perform an action, but these conditions have to be exclusive, meaning if those 3 buttons are highlighted but any other one as well the action won't perform, an other will (different actions for instance if only litPad[3] & litPad[6] are highlighted/true or if litPad[3], litPad[6], litPad[12] & litPad[19] are highlighted/true).

I can't seem to format correctly my if statements to match what I want to achieve.

Thanks in advance !!

Upvotes: 0

Views: 74

Answers (2)

matt
matt

Reputation: 535801

You have a series of actions based on very specific patterns of "which ones are true", so just match against those patterns:

switch whichAreTrue {
    case [3,6,12]: doOneThing()
    case [3,6]: doAnotherThing()
    // ...
    default:break
}

I suppose the question then is: given an array of Bools, how do you know "which are true"? How do you derive the index numbers from the thing itself? Like this:

let arr = [true, false, true, false, false, true, false]
let whichAreTrue = arr.enumerated().filter{$0.1}.map{$0.0} // [0, 2, 5]

And now you have something you can match against.

Upvotes: 1

Gereon
Gereon

Reputation: 17872

You can use a Set to keep track of which buttons are "on", and then build a switch statement for the individual actions:

var litPad = Set<Int>()

litPad = [ 1,2,5 ]

switch litPad {
case [1,2,5]: print("action 1")
case [1,2]: print("action 2")
default: ()
}

Upvotes: 2

Related Questions