嵌套枚举的最佳方法是通过Swift中的switch语句进行访问?

嵌套枚举的最佳方法是通过Swift中的switch语句进行访问?,第1张

概述我有一个像这样的嵌套枚举,用于描述基本的相对定位: enum Location { enum Top { case Left case Right case Center } enum Bottom { case Left case Right case Center } enum Le @H_403_2@ 我有一个像这样的嵌套枚举,用于描述基本的相对定位:

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")}
@H_403_2@ 总结

以上是内存溢出为你收集整理的嵌套枚举的最佳方法是通过Swift中的switch语句进行访问?全部内容,希望文章能够帮你解决嵌套枚举的最佳方法是通过Swift中的switch语句进行访问?所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/web/1003919.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-22
下一篇 2022-05-22

发表评论

登录后才能评论

评论列表(0条)

保存