我正在编写一个递归下降解析器。我希望我的解析器能够处理 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)'
这令人费解,因为:
-
dropFirst
返回Self.SubSequence
-
CollectionType.SubSequence
是SubSequence : Indexable, SequenceType = Slice<Self>
-
Slice
是CollectionType
. - 因此,
m
应该是CollectionType
.
但是由于某些原因,这不起作用。如何定义 unpack
所以它可以递归传递子序列?
最佳答案
Swift 中不再有 CollectionType
。 Array
和ArraySlice
都采用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/