[英]Getting “Binary operator ~= cannot be applied to two (Int, Int) operands” in Swift switch statement with (Int, Int) tuple cases
[英]Swift switch statement considered all cases of Int, but compiler still display error
我理解Swift中的switch語句必須是詳盡的,否則我們必須提供一個默認的情況。 我在網上看到了下面的代碼,switch語句已經涵蓋了Int中的所有情況,但是編譯器仍然顯示錯誤消息,交換機必須是詳盡的,考慮添加一個default子句。 有什么我想念的嗎?
extension Int {
enum Kind {
case Negative, Zero, Positive
}
var kind: Kind {
switch self {
case 0:
return .Zero
case let x where x > 0:
return .Positive
case let x where x < 0:
return .Negative
}
}
}
更新Swift 3: Swift 3引入了ClosedRange
,它可以定義一個范圍,如1...Int.max
包括最大可能的整數(比較Swift 3中的范圍 )。 所以這個編譯並按預期工作,但仍然需要一個默認的情況來滿足編譯器:
extension Int {
enum Kind {
case negative, zero, positive
}
var kind: Kind {
switch self {
case 0:
return .zero
case 1...Int.max:
return .positive
case Int.min...(-1):
return .negative
default:
fatalError("Oops, this should not happen")
}
}
}
還有其他錯誤報告,其中Swift編譯器無法正確確定switch語句的詳盡性,例如https://bugs.swift.org/browse/SR-766,Apple工程師Joe Groff評論說:
不幸的是,像'...'和'<'這樣的整數運算只是Swift的簡單函數,因此很難進行這種分析。 即使對特殊情況理解整數區間,我認為仍然存在模式匹配的完全普遍性的情況,其中窮舉匹配將是不可判定的。 我們最終可能能夠處理一些案件,但這樣做總會遇到特殊情況。
舊答案:編譯器並不是很聰明地認識到你已經涵蓋了所有可能的情況。 一種可能的解決方案是使用fatalError()
添加默認情況:
var kind: Kind {
switch self {
case 0:
return .Zero
case let x where x > 0:
return .Positive
case let x where x < 0:
return .Negative
default:
fatalError("Oops, this should not happen")
}
}
或者使case 0:
默認情況:
var kind: Kind {
switch self {
case let x where x > 0:
return .Positive
case let x where x < 0:
return .Negative
default:
return .Zero
}
}
( 備注:我最初認為以下內容可以正常工作而無需默認情況:
var kind: Kind {
switch self {
case 0:
return .Zero
case 1 ... Int.max:
return .Positive
case Int.min ... -1:
return .Negative
}
}
但是,這會編譯 ,但會在運行時中止,因為您無法創建范圍1 ... Int.max
。 有關此問題的更多信息,請參閱Swift中的Ranges和Intervals一文 。)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.