我有一个这样的嵌套枚举,用于描述基本的相对定位。
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
语句,但没有一个enums显示为可能的情况,如果我试图列出它们,我得到一个错误。
func switchOverEnum(enumCase: Location) {
switch enumCase {
case .Top:
print("hey this didn't cause an error whoops no it did")
}
}
错误是: Enum case 'Top' not found in type 'Location'.
现在有一个版本的问题 此处根据最有用的答案,应该这样做。
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")
}