2016-11-16 81 views
0

我想使用pageControl.currentPage跟蹤我的頁面,它返回一個整數。我的switch語句設置像這樣:如何爲pageControl.currentPage創建一個枚舉?

let currentPage = pageControl.currentPage 
switch currentPage { 
case 0: 

// execute code for first page 

case 1: 

// execute code for second page 

case 2: 

// execute code for third page 

default: break 
} 

的情況下,而不是 「0」, 「1」 和 「2」,我想更多的語義如

case FirstPage: 
case SecondPage: 
case ThirdPage: 

如何我會這樣做嗎?

回答

3

你最好的選擇是用Int的值支持enum。

你可以聲明枚舉像這樣:

enum PageEnum: Int { 
    case firstPage = 0 // Implicitly 0 if you don't set value for first enum. 
    case secondPage = 1 // Each enum after will automatically increase by 1 
    case thirdPage = 2 // so explicitly listing raw value is not necessary. 
} 

然後,您可以使用一個開關來確定,像這樣的頁面值:

switch PageEnum(rawValue: currentPage)! { 
    case .firstPage: 
    print("You're on the first page") 
    case .secondPage: 
    print("You're on the second page") 
    case .thirdPage: 
    print("You're on the third page") 
    default: 
    assert(false, "You shouldn't ever land here") 
} 
+0

不錯!我只是從中學到了一些東西。一個很好的副作用 - 當我嘗試代碼時,編譯器警告我「永遠不會達到」默認情況。我假設,如果你通過了一個pageControl.currentPage值爲4的應用程序會崩潰。 – dfd

+0

是的,它會崩潰,因爲failable初始化程序('PageEnum(rawValue:currentPage)!')的解開力量。有可能使用一些更安全的語法,但我目前不知道它在我頭頂。 – AdamPro13