加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

Swift 3中最小的工作IteratorProtocol/Sequence

发布时间:2020-12-14 04:59:16 所属栏目:百科 来源:网络整理
导读:我发现在 Swift 3中使用Sequence / IteratorProtocol找到“工作文档”非常困难.有些教程/文章似乎适用于较旧的Swift. 想象一下名为DLList的玩具双链表类… public class Node { // whatever "thing" you have a group of,this is that "thing" }public class
我发现在 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(例如,当您实现包装器时).所以,分裂确实对我有意义.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读