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?
Two problems:
<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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With