大佬教程收集整理的这篇文章主要介绍了Swift 3中最小的工作IteratorProtocol/Sequence,大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
想象一下名为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) } }
您似乎只需@L_342_3@makeIterator调用即可.
第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(例如,当您实现包装器时).所以,分裂确实对我有意义.
以上是大佬教程为你收集整理的Swift 3中最小的工作IteratorProtocol/Sequence全部内容,希望文章能够帮你解决Swift 3中最小的工作IteratorProtocol/Sequence所遇到的程序开发问题。
如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。