Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift guard statement pattern matching with enum

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:

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?

like image 562
Leonardo Marques Avatar asked Dec 10 '22 18:12

Leonardo Marques


1 Answers

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(...).

Therefore:

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

or, using the equivalent x? pattern:

guard case let .Head(element: e, next: _)? = head
like image 199
Martin R Avatar answered Jan 04 '23 23:01

Martin R