Swift 3中最小的工作IteratorProtocolSequence

Swift 3中最小的工作IteratorProtocolSequence,第1张

概述我发现在 Swift 3中使用Sequence / IteratorProtocol找到“工作文档”非常困难.有些教程/文章似乎适用于较旧的Swift. 想象一下名为DLList的玩具双链表类… public class Node { // whatever "thing" you have a group of, this is that "thing" }public 我发现在 Swift 3中使用Sequence / IteratorProtocol找到“工作文档”非常困难.有些教程/文章似乎适用于较旧的Swift.

想象一下名为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)        }    }

您似乎只需添加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成为一个非常好的迭代器时还有更多工作要做吗?

解决方法 这一切都很好地通过类型推断(在Swift中非常强大的东西).

例如. 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所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/web/1017486.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-05-23
下一篇2022-05-23

发表评论

登录后才能评论

评论列表(0条)

    保存