Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make a switch for an array?

Here's my code:

var animalArray = ["cow","pig"]

switch animalArray {
case ["cow","pig"],["pig","cow"]:
    println("You Win!")
default:
    println("Keep Trying")

I get the error: "Type 'Array' does not conform to protocol 'IntervalType'" for the line "case ["cow","pig"],["pig","cow"]:". What am I doing wrong?

like image 562
Michael Longenecker Avatar asked Feb 16 '15 15:02

Michael Longenecker


People also ask

Can you switch an array?

Yes, you can pass an array to a switch. The catch is that I'm not talking about Java arrays, but a data structure. An array is a systematic arrangement of objects, usually in rows and columns.

Can we use array in switch case in C?

In C, you cannot use arrays in switch (and expressions for case ). Also, the type passed to switch() and types specified in each case must match.

What is switch () in Java?

The switch case in java executes one statement from multiple ones. Thus, it is like an if-else-if ladder statement. It works with a lot of data types. The switch statement is used to test the equality of a variable against several values specified in the test cases.

Can you do a switch on a string?

Yes, we can use a switch statement with Strings in Java. While doing so you need to keep the following points in mind. It is recommended to use String values in a switch statement if the data you are dealing with is also Strings.


1 Answers

You can't do that with an array. But you could check it with the contains() method and iterate over the array you want to test(here secondArray):

var animalArray:[String] = ["cow", "pig"]
var secondArray:[String] = ["cow", "test"]

for s in secondArray{
    if(contains(animalArray, s)){
        println("animalArray Contains \(s)")
    }
}
like image 166
Christian Avatar answered Sep 29 '22 06:09

Christian