我有一个像这样的嵌套枚举,用于描述基本的相对定位: 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 Rig
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") } }
错误是:在“位置”类型中找不到枚举案例“顶部”.
现在有一个问题here的版本,根据最有用的答案,应该这样做:
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") }