How to make a switch for an array?

Here is 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 match the" IntervalType "protocol for the string" case ["cow", "pig"], ["pig", "cow"]: "What am I doing wrong?

+4
source share
5 answers

The operator switchrequires Int. Think about it:

var animalDict: [String: Int] = ["cow": 0,"pig": 1]
var animalSelection: Int = animalDict["cow"]!

switch animalSelection {
case 0:
    println("The Cow Wins!")
case 1:
    println("The Pig Wins!")
default:
    println("Keep Trying")
}

//prints "The Cow Wins!"


Change 1:

Thank you all for your comments. I think this is more reliable code:

var animalDict: [String: Int] = ["cow": 0,"pig": 1]
var animalSelection: Int? = animalDict["horse"]

if animalSelection as Int? != nil {
   switch animalSelection! {
   case 0:
       println("The Cow Wins!")
   case 1:
       println("The Pig Wins!")
   default:
       println("Keep Trying")
   }
} else {
    println("Keep Trying")
}

//prints "Keep Trying"

He will print The Cow Winsif I say:

var animalSelection:Int? = animalDict["cow"]


Edit 2:

Based on @AirSpeedVelocity's comments, I checked the following code. Much more elegant than my own code:

var animalDict: [String: Int] = ["cow": 0,"pig": 1]
var animalSelection = animalDict["horse"]

switch animalSelection {
case .Some(0):
    println("The Cow Wins!")
case .Some(1):
    println("The Pig Wins!")
case .None:
    println("Not a valid Selection")
default:
    println("Keep Trying")
}
+1

. contains() , ( secondArray):

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

for s in secondArray{
    if(contains(animalArray, s)){
        println("animalArray Contains \(s)")
    }
}
+2

If you want to compare two arrays regardless of the order of their entries, I would suggest the following:

      var referenceAnimal = ["cow", "pig"]
      var animalsToTest = ["pig", "cow"]


      sort(&referenceAnimal)
      sort(&animalsToTest)


      if referenceAnimal == animalsToTest {
          println("You Win!")
      } else {
          println("Keep Trying")
      }
+1
source

You can make it switchable to map arrays by overloading accordingly ~=:

func ~=<T: Equatable>(lhs: [T], rhs: [T]) -> Bool {
    return lhs == rhs
}

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

switch animalArray {
case ["cow","pig"],["pig","cow"]:
    println("You Win!")  // this will now match
default:
    println("Keep Trying")
}

Its doubtful, however, is a good idea.

0
source

This is almost identical to @Christian Woerz's answer, but in these situations I join reduce.

var animalArray = ["cow","pig"]
var answerArray = ["pig","cow"]
let isCorrect = answerArray.reduce(true) { bool, animal in
    return bool && contains(animalArray, animal)
}
0
source

All Articles