【问题标题】:Recursively parse a CollectionType递归解析 CollectionType
【发布时间】:2016-03-08 13:49:50
【问题描述】:

我正在编写一个递归下降解析器。我希望我的解析器可以处理UInt8 的任何(或至少“许多”)集合(例如,不仅是 Swift.Array)

func unpack<T: CollectionType where T.Generator.Element == UInt8>(t: T) {
    let m = t.dropFirst()
    //[do actual parsing here]
    unpack(m)
}

但是:

error: cannot invoke 'unpack' with an argument list of type '(T.SubSequence)'
note: expected an argument list of type '(T)'

这很令人费解,因为:

  1. dropFirst 返回Self.SubSequence
  2. CollectionType.SubSequenceSubSequence : Indexable, SequenceType = Slice&lt;Self&gt;
  3. SliceCollectionType
  4. 因此,m 应该是 CollectionType

但是由于某种原因,这不起作用。如何定义unpack 以便递归传递子序列?

【问题讨论】:

标签: swift generics recursion types


【解决方案1】:

Swift 中不再有CollectionTypeArrayArraySlice 都采用 Sequence。您使用的dropFirst() 方法在Sequence 中声明。所以你可以像这样制作递归泛型函数:

func unpack<T: Sequence>(t: T) where T.Element == UInt8 {
    let m = t.dropFirst()
    //[do actual parsing here]
    unpack(m)
}

【讨论】:

    猜你喜欢
    • 2011-05-05
    • 2015-08-03
    • 2011-10-10
    • 1970-01-01
    • 2018-09-30
    • 2012-08-11
    • 2014-04-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多