Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to compare one value against multiple values - Swift

Let's say that you have the code

if stringValue == "ab" || stringValue == "bc" || stringValue == "cd" {     // do something } 

Is there a way to shorten this condition or beautify it (preferably without using the switch statement)? I know that this code does NOT work:

if stringValue == ("ab" || "bc" || "cd") {     // do something } 

I've seen some complex solutions on other languages, but they seem language specific and not applicable to Swift. Any solutions would be appreciated.

like image 942
ICanCYou Avatar asked Sep 23 '15 21:09

ICanCYou


People also ask

How do you compare multiple values in an if statement?

To check if a variable is equal to all of multiple values, use the logical AND (&&) operator to chain multiple equality comparisons. If all comparisons return true , all values are equal to the variable. Copied! We used the logical AND (&&) operator to chain multiple equality checks.

How do you compare variables?

Use scatterplots to compare two continuous variables. Use scatterplot matrices to compare several pairs of continuous variables. Use side-by-side box plots to compare one continuous and one categorical variable. Use variability charts to compare one continuous Y variable to one or more categorical X variables.

What is the correct way to compare the equality of two string type objects in Swift?

To check if two strings are equal in Swift, use equal to operator == with the two strings as operands. The equal to operator returns true if both the strings are equal or false if the strings are not equal.


1 Answers

let valuesArray = ["ab","bc","cd"]  valuesArray.contains(str) // -> Bool 
like image 169
Aaron Avatar answered Sep 18 '22 13:09

Aaron