【问题标题】:Swift guard statement pattern matching with enumSwift 守卫语句模式与枚举匹配
【发布时间】:2016-02-29 12:09:06
【问题描述】:

我正在尝试返回我自己在 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)
}

和这样的列表实现:

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&lt;Element&gt; 并保持它像guard case let .Head(element: e, next: _) = head 它给我"Enum case 'Head' not found in 'guard case let DLLNode&lt;Element&gt;.Head(element: e, next: _) = head'" 我究竟做错了什么?或者也许有更好的方法来做到这一点?

【问题讨论】:

    标签: swift enums pattern-matching


    【解决方案1】:

    两个问题:

    • 您不得在模式中重复通用占位符&lt;Element&gt;
    • head 是一个可选,所以你必须匹配它 .Some(...)

    因此:

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

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

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

    【讨论】:

      猜你喜欢
      • 2011-09-28
      • 2019-03-01
      • 2022-11-21
      • 1970-01-01
      • 2015-08-15
      • 1970-01-01
      • 1970-01-01
      • 2017-06-23
      • 1970-01-01
      相关资源
      最近更新 更多