enum Location {
enum Top {
case Left
case Right
case Center
}
enum Bottom {
case Left
case Right
case Center
}
enum Left {
case Top
case Bottom
case Center
}
enum Right {
case Top
case Bottom
case Center
}
enum Center {
case Center
}
}
如果我尝试运行switch声明,没有任何枚举显示为可能的情况,如果我尝试列出它们,我会收到错误:
func switchOverEnum(enumCase: Location) {
switch enumCase {
case .Top:
print("hey this didn't cause an error whoops no it did")
}
}
enum Location {
enum TopLocations {
case Left
case Right
case Center
}
enum BottomLocations {
case Left
case Right
case Center
}
enum LeftLocations {
case Top
case Bottom
case Center
}
enum RightLocations {
case Top
case Bottom
case Center
}
enum CenterLocations {
case Top
case Bottom
case Left
case Right
case Center
}
case Top(TopLocations)
case Bottom(BottomLocations)
case Left(LeftLocations)
case Right(RightLocations)
case Center(CenterLocations)
}
这完全有效,但看起来有点笨重,或者不优雅,或者不像 Swift。这真的是最简洁的方式吗?
我认为用两个枚举和一个元组可以更简洁地表达这一点。在操场上试试这个:
enum HorizontalPosition {
case Left
case Right
case Center
}
enum VerticalPosition {
case Top
case Bottom
case Center
}
typealias Location = (horizontal: HorizontalPosition, vertical: VerticalPosition)
let aLocation = Location(horizontal: .Left, vertical: .Bottom)
switch aLocation {
case (.Left, .Bottom): print ("left bottom")
case (.Center, .Center): print ("center center")
default: print ("everything else")
}