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?
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.
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.
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.
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.
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)")
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With