gpt4 book ai didi

swift - 递归解析 CollectionType

转载 作者:行者123 更新时间:2023-11-28 08:51:33 26 4
gpt4 key购买 nike

我正在编写一个递归下降解析器。我希望我的解析器能够处理 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<Self>
  3. SliceCollectionType .
  4. 因此,m应该是 CollectionType .

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

最佳答案

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

关于swift - 递归解析 CollectionType,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34074624/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com