想象一下名为DLList的玩具双链表类…
public class Node { // whatever "thing" you have a group of,this is that "thing" } public class DLList { // toy linked list class here // so this is a group of "node" in this example }
我相信下面代表了最简单的(?),正确的方法,总而言之,你可以在for结构中使用DLList.
第1步,让你的DLList符合DLList:Sequence
public class DLList:Sequence { // toy linked list class here public func makeIterator() -> DLListIterator { return DLListIterator(self) } }
第2步,编写迭代器,符合IteratorProtocol
由于该类是DLList,我们将其称为DLListIterator.看起来似乎是这样
1,你必须有一个“init”,基本上是有问题的组类
2,你必须有一个下一个电话,它必须返回一个与你的小组类神奇相关的“事物”.
public class DLListIterator:IteratorProtocol { var dll:DLList // you must kNow the group in question var pointer:Node? // you must kNow where you are init(_ dll:DLList) { // so note those two items self.dll = dll self.pointer = dll.firstOne } public func next() -> Node? { // return the next one; careful to return nil at end. let thisOne = self.pointer self.pointer = self.pointer?.nextOne return thisOne } }
这似乎完美无缺.也就是说,你现在可以去了
var d:DLList = DLList() for n in d { print or whatever n }
你可以使用e = d.filter({d.item blah})等等 – 很棒.
问题 – 有很多关于相关类型的讨论.在第1部分中,您是否以某种方式明确声明/添加“关联类型”?即使没有明确要求你会如何明确地做到这一点?这种相关类型的业务到底是什么?
问题 – 在第二部分中,我完全不知道它是如何“知道”Node是与DLList相关的“事物”.有没有办法明确表达,或者我不理解什么?
迅捷而且,整个事情看起来不是很迅速.这样做只是为了添加迭代器输出似乎令人难以置信.对于真正的类,在Swift3中有一种更快捷的方式吗? (不是像“倒计时数字”这样的愚蠢的例子.)
最后的问题我高兴地提到上面现在允许和.filter.事实上,我的例子是“完整的” – 我现在可以用DLList做一切“iterator-wise”,一个人可以在Swift中正常做 – 我可能“忘记了一些功能”或者??在使DLList成为一个非常好的迭代器时还有更多工作要做吗?
解决方法
例如. IteratorProtocol只有一个要求,即next() – >元件?方法.如果你只是在XCode中点击IteratorProtocol,你可以看到以下内容:
public protocol IteratorProtocol { associatedtype Element public mutating func next() -> Self.Element? }
因此,如果您声明一个类型符合IteratorProtocol并提供一些next()的实现 – >富?然后Swift立即推断出Foo必须是一个元素.
当然,您可以通过以下方式明确声明:
public class DLListIterator: IteratorProtocol { public typealias Element = Node public func next() -> Element? { // ... } }
并且,是的,一旦你实现了(序列和迭代器,即),你可以做其他序列可以做的所有事情.所有这一切都归功于默认协议实现.
是否所有这些样板文件为了符合Sequence你需要提供makeIterator(),那反过来必须提供next(),是不是Swifty ..我认为这是更多基于意见的东西.有时,您可以实现Sequence而无需实现IteratorProtocol(例如,当您实现包装器时).所以,分裂确实对我有意义.
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。