Better approach than if…else if… else for multiple conditions?

Hi,

I have 4 conditions, which could either be true or false (let’s call them a, b, c, and d). If a condition is set to true, I want to display some text, if it is set to false, no text will be displayed.

Combining all possible conditions, there are in total 16 different outcomes, for example

a == true, b == true, c == true, d == true
Text(a1) Text (b1) Text (c1) Text (d1)
or
a == true, b == false, c == false, d == true
Text(a1), Text(d1)

As a bonus challenge, in another part of the app, based on the same conditions, I want to show different data, for example
A == true, b == false, C == false, D == true
Text(a2), Text(d2)

Writing all 16 possibilities with if… else if … else is doable, but it seems that this is not the most efficient approach, especially if you think to add another condition in the future.

Is there any better approach to compute those conditions and create the desired output?

Just to clarify: Code looks more or less like
If a == true && b == true && c == true && d == true { Text((a) (b) (c) (d)) }
Else if a == false && b == true && c == true && d == true { Text((b) (c) (d)) }
Else if a == true && b == false && c == true && d == true { Text((a) (c) (d)) }
… // 12 more else if clauses
else a == false && b == false && c == false && d == false { Text(„No data“) }

How about making an array of the Text arguments. Let’s say they’re Strings

var myStuff = [String]()
if a { myStuff.append(a) }
if b ( myStuff.append(b) }
if c { myStuff.append(c) }
if d { myStuff.append(d) }
Text(myStuff.joined() )

May not be exactly what you want, but it’s a start.

Great idea, thanks a lot :slight_smile:
Yes, storing the corresponding texts in an array is a great solution. I can loop over them and add some more details (white spaces, commas, dots, whatsoever) in between the texts.

Awesome :slight_smile:

Check out the joined() method. It might save you some looping.

1 Like