这是我的代码:
var animalArray = ["cow","pig"]
switch animalArray {
case ["cow","pig"],["pig","cow"]:
println("You Win!")
default:
println("Keep Trying")
我收到错误:"输入'数组'不符合协议' IntervalType'"对于线"案例["牛","猪"],["猪","牛"]:&# 34 ;.我究竟做错了什么?
答案 0 :(得分:2)
你不能用数组做到这一点。但您可以使用contains()
方法进行检查并迭代要测试的数组(此处为secondArray
):
var animalArray:[String] = ["cow", "pig"]
var secondArray:[String] = ["cow", "test"]
for s in secondArray{
if(contains(animalArray, s)){
println("animalArray Contains \(s)")
}
}
答案 1 :(得分:1)
switch
语句需要Int
。想一想:
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!"
感谢大家的评论。我认为这是更健壮的代码:
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"
如果我说:
,它仍会打印The Cow Wins
var animalSelection:Int? = animalDict["cow"]
根据@ AirSpeedVelocity的评论,我测试了以下代码。比我自己的代码更优雅:
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")
}
答案 2 :(得分:1)
如果您想要的是比较两个数组而不管其条目的顺序如何,那么我建议如下:
var referenceAnimal = ["cow", "pig"]
var animalsToTest = ["pig", "cow"]
sort(&referenceAnimal)
sort(&animalsToTest)
if referenceAnimal == animalsToTest {
println("You Win!")
} else {
println("Keep Trying")
}
答案 3 :(得分:1)
如果订单不重要,则可以这样做。
import Foundation
let animalArray = ["cow","pig"]
extension Array where Element == String {
static func ~=(pattern: Array, value: Array) -> Bool {
return pattern == value
}
}
switch animalArray {
case ["cow", "pig"], ["pig","cow"]:
print("You Win!")
default:
print("Keep Trying")
}
请记住,这会将它应用于您可能希望将其包装的所有Array<String>
上,或者将其应用于所有Equatable
。
答案 4 :(得分:0)
您可以通过适当地重载switch
来使~=
能够匹配数组:
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")
}
这是否是一个好主意是值得怀疑的。
答案 5 :(得分:0)
这与@Christian Woerz的答案几乎完全相同,但在这些情况下我是reduce
的傻逼。
var animalArray = ["cow","pig"]
var answerArray = ["pig","cow"]
let isCorrect = answerArray.reduce(true) { bool, animal in
return bool && contains(animalArray, animal)
}
答案 6 :(得分:0)
为了将来参考,将开关包装在for-in循环中是另一种选择。
var animalArray = ["cow", "pig"]
for animal in animalArray {
switch animal {
case "cow":
print("win")
case "pig":
print("lose")
default:
print("try again")
}
}