本文介绍了递归解析CollectionType的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在编写一个递归下降解析器.我希望我的解析器可以处理UInt8
的任何(或至少很多")集合(例如,不仅是Swift.Array)
I'm writing a recursive descent parser. I'd like my parser to work on any (or at least "many") Collections of UInt8
(e.g., not only 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
.
dropFirst
returnsSelf.SubSequence
CollectionType.SubSequence
isSubSequence : Indexable, SequenceType = Slice<Self>
Slice
isCollectionType
.- Therefore,
m
should beCollectionType
.
但是由于某些原因,这是行不通的.如何定义unpack
以便可以递归传递子序列?
However for some reason, this doesn't work. How do I define unpack
so it can be recursively passed subsequences?
推荐答案
Swift中不再有CollectionType
了. Array
和ArraySlice
都采用 Sequence
.在Sequence
中声明您使用的dropFirst()
方法.因此,您可以像这样制作递归泛型函数:
There is no CollectionType
in Swift anymore. Both Array
and ArraySlice
adopt Sequence
. And the dropFirst()
method which you use is declared in Sequence
. So you can make recursive generic function like this:
func unpack<T: Sequence>(t: T) where T.Element == UInt8 {
let m = t.dropFirst()
//[do actual parsing here]
unpack(m)
}
这篇关于递归解析CollectionType的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!