在 Swift 中嵌套枚举以通过 switch 语句访问的更简洁方法? [关闭]

2024-04-04

我有一个像这样的嵌套枚举,用于描述基本的相对定位:

  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 case 'Top' not found in type 'Location'.

现在这个问题有一个版本here https://stackoverflow.com/questions/34822345/how-do-you-use-a-switch-statement-with-a-nested-enum,根据最有帮助的答案,应该这样做:

   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")
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

在 Swift 中嵌套枚举以通过 switch 语句访问的更简洁方法? [关闭] 的相关文章

随机推荐