2016-11-16 156 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