Swift Guard语句模式与枚举匹配

时间:2021-06-13 22:35:44

I'm trying to return the head element of my own implementation of a Doubly Linked List in Swift. My Nodes are declared as an enum like this:

我试图在Swift中返回我自己实现的双链接列表的head元素。我的节点被声明为这样的枚举:

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

and the list implementation like this:

和列表实现如下:

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

But I'm getting "Invalid pattern" on the guard statement. If I omit the DLLNode<Element> and just keep it like guard case let .Head(element: e, next: _) = head it gives me "Enum case 'Head' not found in 'guard case let DLLNode<Element>.Head(element: e, next: _) = head'" What am I doing wrong? Or maybe there is a better way to do this?

但是我在守卫声明中得到了“无效模式”。如果我省略DLLNode 并保持它像保护案一样让.Head(element:e,next:_)= head它给了我“enum case'Head'找不到'guard case let DLLNode 。头(元素:e,下一个:_)=头'“我做错了什么?或者也许有更好的方法来做到这一点?

1 个解决方案

#1


11  

Two problems:

两个问题:

  • You must not repeat the generic placeholder <Element> in the pattern.
  • 您不能在模式中重复通用占位符
  • head is an optional, so you have to match it against .Some(...).
  • head是可选的,所以你必须将它与.Some(...)匹配。

Therefore:

因此:

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

or, using the equivalent x? pattern:

或者,使用等效的x?模式:

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

#1


11  

Two problems:

两个问题:

  • You must not repeat the generic placeholder <Element> in the pattern.
  • 您不能在模式中重复通用占位符
  • head is an optional, so you have to match it against .Some(...).
  • head是可选的,所以你必须将它与.Some(...)匹配。

Therefore:

因此:

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

or, using the equivalent x? pattern:

或者,使用等效的x?模式:

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