2016-08-04 34 views
-1

以下是用於在操場上執行Switch語句的代碼。我沒有使用默認值就執行了幾個switch語句。我的疑問是爲什麼這是可選的一些和強制性的其他陳述。提前感謝!沒有默認語句的Swift 3.0-Switch語句出錯'開關必須詳盡,考慮添加默認子句'

let someNumber = 3.5 

switch someNumber { 

case 2 , 3 , 5 , 7 , 11 , 13 : 
    print("Prime numbers") 
case 4 , 6 , 24 , 12 , 66 : 
    print("Normal numbers") 

} 

反語句執行成功,而無需使用默認

let yetAnotherPoint = (3,1) 

    switch yetAnotherPoint { 

    case let (x,y) where x == y : 
    print("(\(x),\(y)) is on the line x == y") 
    case let (x,y) where x == -y : 
    print("(\(x),\(y)) is on the line x == -y") 
    case let (x,y): 
    print("(\(x),\(y)) is just some arbitrary point") 

    } 
+0

你是需要涵蓋Swift中所有可能的案例。所以它希望你添加如下內容:'default:print(「其他一些數字」)' – vacawama

+0

我執行了很少的switch語句而不使用默認值。我的疑問是,爲什麼在這個特定的聲明錯誤消息觸發默認爲強制性的。 – Ram

+0

錯誤消息很明顯。每個通過交換機的值都必須通過案例或默認子句進行處理。如果您有反例,請展示。 – vacawama

回答

6

至於其他的評論說,你應該使用default,因爲在你的情況下,你不暴露每一個可能的雙。但是,如果您想了解更多,你這樣做是在你的第二個例子的方式,你可以像下面這樣:

let someNumber = 3.5 
switch someNumber { 
case 2 , 3 , 5 , 7 , 11 , 13 : 
    print("Prime numbers") 
case 4 , 6 , 24 , 12 , 66 : 
    print("Normal numbers") 
case let x: 
    print("I also have this x = \(x)") 
} 
只爲參考

,這裏的這個情景是如何最常處理:

let someNumber = 3.5 
switch someNumber { 
case 2 , 3 , 5 , 7 , 11 , 13 : 
    print("Prime numbers") 
case 4 , 6 , 24 , 12 , 66 : 
    print("Normal numbers") 
default: 
    print("I have an unexpected case.") 
}