更简洁的方法来嵌套枚举以供Swift中的switch语句访问? [英] More concise way to nest enums for access by switch statements in Swift?
问题描述
我有一个这样的嵌套枚举,用于描述基本的相对位置:
I have a nested enum like so, for describing basic relative positioning:
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
语句,则所有枚举都不会出现,如果我尝试列出它们,则会出现错误:
If I try to run a switch
statement with it, none of the enums show up as possible cases, and if I try to list them I get an error:
func switchOverEnum(enumCase: Location) {
switch enumCase {
case .Top:
print("hey this didn't cause an error whoops no it did")
}
}
错误为: 在'Location'类型中找不到枚举'Top'。
现在有此问题的版本此处,并根据最有帮助的答案,应该这样完成:
Now there's a version of this question here, and according to the most helpful answer, it should be done like this:
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)
}
虽然完全可以使用,但似乎有点笨拙,笨拙或不敏捷。这真的是最简洁的方法吗?
Which totally works, but seems a bit clunky, or inelegant, or un-Swift-like. Is this really the most concise way?
推荐答案
我认为用两个枚举和一个元组来更简洁地表达它。在操场上尝试:
I think this would be much more concisely expressed with two enums and a tuple. Try this in a playground:
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")
}
这篇关于更简洁的方法来嵌套枚举以供Swift中的switch语句访问?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!