[英]How to check all cases in a switch statement in swift using where keyword?
當我執行此代碼時,只執行了print("it is greater than zero")
,但是有兩種情況為真,我嘗試使用fallthrough
關鍵字,但是即使它為false,它也會執行下一個case塊,否有什么關系,
這又引發了另一個問題,何時應使用fallthrough
關鍵字? 如果我要強制執行下一個塊,為什么不只是將代碼插入到在同一個塊fallthrough
坐鎮?
有什么辦法可以使下面的示例打印出所有評估結果為true的案例,但仍排除所有評估結果為false的案例?
let number = 1
switch number {
case _ where number > 0:
print("it is greater than zero")
case _ where number < 2:
print("it is less than two")
case _ where number < 0:
print("it is less than zero")
default:
print("default")
}
預先感謝您的回答!
switch
語句不是用於此目的,並且不能以這種方式工作。 目的是找到一個真實的案例。 如果要檢查多種情況,那只是一個if
語句:
let number = 1
if number > 0 {
print("it is greater than zero")
}
if number < 2 {
print("it is less than two")
}
if number < 0 {
print("it is less than zero")
}
沒有與此等效的switch
。 它們是不同的控制語句。
正如您所發現的,存在fallthrough
以允許兩種情況運行同一塊。 這就是它的目的; 它不會檢查其他情況。 通常,如果您廣泛使用case _
,則可能未在Swift中正確使用switch
,應使用if
。
您是正確的,即fallthrough
意味着“在不檢查其真值的情況下進行下一種情況 ”。
因此,如果只想在兩種情況都成立的情況下執行第一種情況和第二種情況,則必須將第二種檢查作為第一種情況的一部分進行。 因此,對您的代碼的最小更改是:
let number = 1
switch number {
case _ where number > 0:
print("it is greater than zero")
if number < 2 { fallthrough } // <--
case _ where number < 2:
print("it is less than two")
case _ where number < 0:
print("it is less than zero")
default:
print("default")
}
但是,這不是我編寫此特定示例的方式。 而且無論如何,您仍然面臨當數字為-1時會發生什么的問題。 小於2但小於0,因此您再次遇到相同的問題。 從您的問題根本看不出這里的實際目標是什么! 如果這確實是您要檢測的三件事,那么最好使用兩個單獨的測試,因為它們之間並不是很明確的關聯。 例如:
let number = 1
switch number {
case ..<0:
print("it is less than zero")
case 0...:
print("it is zero or greater")
default: break
}
switch number {
case ..<2:
print("it is less than two")
default: break
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.