我一直在努力ForwardIndexType为枚举正确实现协议,特别是最终案例的处理(即没有后继的最后一项).Swift语言书中没有涵盖这个协议.
这是一个简单的例子
enum ThreeWords : Int, ForwardIndexType {
case one=1, two, three
func successor() ->ThreeWords {
return ThreeWords(rawValue:self.rawValue + 1)!
}
}
Run Code Online (Sandbox Code Playgroud)
该successor()函数将返回下一个枚举器值,但最后一个元素除外,它将因异常而失败,因为之后没有值.three
在ForwardTypeProtocol不允许successor()返回一个条件值,所以似乎没有信号,没有继任者的方式.
现在在for循环中使用它来迭代枚举的所有可能值的闭合范围,对于最终情况会遇到问题:
for word in ThreeWords.one...ThreeWords.three {
print(" \(word.rawValue)")
}
println()
//Crashes with the error:
fatal error: unexpectedly found nil while unwrapping an Optional value
Run Code Online (Sandbox Code Playgroud)
successor()在执行for循环中的语句之前,Swift莫名其妙地调用范围的结束值的函数.如果范围保持半开,ThreeWords.one..<ThreeWords.three则代码正确执行,打印1 2
如果我修改后继函数,以便它不会尝试创建大于.three这个值的值
func successor() ->ThreeWords {
if self == .three {
return .three
} else { …Run Code Online (Sandbox Code Playgroud)