2016-07-12 50 views
4

我有一個嵌套的枚舉像這樣,用於描述基本相對定位:在Swift中通過switch語句嵌套枚舉的最佳方法是什麼?

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的一個版本,並根據最有用的答案,它SH烏爾德就像這樣:

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) 
    } 

其中全部工作,但似乎有點笨重,或不雅,或取消雨燕樣。這真的是最好的方法嗎?

+1

爲什麼它是不動搖的?它給了一個簡單的事情最大的複雜性這是完全swifty。 –

+0

不清楚你在問什麼。你的原創只是愚蠢的('.Top'不是一個位置的例子,它是一個嵌套的枚舉,所以很難想象你期待什麼),「最好的方式」是一個意見問題。 – matt

+0

我投票結束這個問題主要基於意見,因爲答案只能基於意見和偏好,而不是事實。考慮發佈到[代碼評論](http://codereview.stackexchange.com)一個完整的,真實的例子。 – JAL

回答

3

我認爲這將用兩個枚舉和一個元組更簡潔地表達。試試這個在操場上:

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") 
} 
+0

即使問題已經結束,您應該得到一些信用:這是一個很好的答案。謝謝! –

+0

@LeMotJuiced謝謝!我希望我能夠提供幫助 –

相關問題