![](/img/trans.png)
[英]How to compare switch case with UIViewController as input in swift 2
[英]Is there a way to compare array with array using switch case in Swift?
我已經嘗試過使用if比較數組與數組:
let ArrayA = ["A", "B"]
if ArrayA == ["A", "B"] {
print("true")
} else {
print("false")
}
結果將是true
,那么我們如何使用switch和case? 使用Swift語言可以做到嗎?
您可以使用的情況下where
謂詞:
let array = ["A", "B"]
switch array {
case _ where array == ["A", "B"]: print("AB")
case _ where array == ["C", "D"]: print("CD")
default: print("default")
}
如果確實需要,可以定義調用==
的模式匹配運算符( ~=
)。 該switch
語句查找模式匹配運營商接受給定的模式和候選,以確定是否定義case
匹配:
let array = ["A", "B"]
func ~= <T: Equatable>(pattern: [T], candidate: [T]) -> Bool {
return pattern == candidate
}
switch array {
case ["A", "B"]: print("AB")
case ["C", "D"]: print("CD")
default: print("default")
}
我建議不要這樣做,因為尚不清楚這種情況是否在執行==
檢查, contains(_:)
, hasPrefix(_:)
等。
在Swift中切換可以使用許多不同的類型,但是它與開箱即用的數組不匹配。 您可以通過適當地重載〜=來匹配數組
func ~=<T: Equatable>(lhs: [T], rhs: [T]) -> Bool {
return lhs == rhs
}
let ArrayA = ["A","B"]
switch ArrayA {
case (["A","B"]):
print("true")
default:
print("false")
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.