2016-02-29 82 views
3

我試圖返回我自己在Swift中實現雙向鏈表的頭元素。 我的節點被聲明爲這樣一個枚舉:Swift guard語句模式與枚舉匹配

enum DLLNode<Element>{ 
    indirect case Head(element: Element, next: DLLNode<Element>) 
    indirect case Node(prev: DLLNode<Element>, element: Element, next: DLLNode<Element>) 
    indirect case Tail(prev: DLLNode<Element>, element: Element) 
} 

和列表實現這樣的:

struct DLList<Element> { 
    var head:DLLNode<Element>? 

... 

func getFirst()throws->Element{ 
     if self.isEmpty(){ 
      throw ListError.EmptyList(msg: "") 
     } 
     guard case let DLLNode<Element>.Head(element: e, next: _) = head 
      else{ 
       throw ListError.UnknownError(msg: "") 
     } 
     return e 
    } 
} 

但是我卻越來越"Invalid pattern"在保護聲明。如果我省略了DLLNode<Element>,只是保持它像guard case let .Head(element: e, next: _) = head它給我"Enum case 'Head' not found in 'guard case let DLLNode<Element>.Head(element: e, next: _) = head'" 我做錯了什麼?或者也許有更好的方法來做到這一點?

回答

9

兩個問題:

  • 不得重複仿製佔位<Element>的格局。
  • head可選,所以你必須匹配它與 .Some(...)

因此:

guard case let .Some(.Head(element: e, next: _)) = head 

,或者利用等效x?圖案:

guard case let .Head(element: e, next: _)? = head