嵌套枚举的最佳方法是通过Swift中的switch语句进行访问?
发布时间:2020-12-14 04:34:12 所属栏目:百科 来源:网络整理
导读:我有一个像这样的嵌套枚举,用于描述基本的相对定位: 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 Bott
我有一个像这样的嵌套枚举,用于描述基本的相对定位:
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") } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |