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