2. Swift IteratorProtocol

IteratorProtocol协议和Sequence的联系是非常紧密的。序列通过创建一个迭代器来访问它们的元素,迭代器跟踪它的迭代过程并在它通过序列前进时每次返回一个元素。

当你在array, set, 或者其他集合和序列使用for - in的时候就会用到这个类型的迭代器。swift使用队列或者集合的内部迭代器以便使用for - in这种语言结构。

直接使用迭代器遍历元素和用for - in遍历同一个数组是等价的。比如你使用for - in遍历数组["Antelope", "Butterfly", "Camel", "Dolphin"]

     let animals = ["Antelope", "Butterfly", "Camel", "Dolphin"]
     for animal in animals {
        print(animal)
     }
     // Prints "Antelope"
     // Prints "Butterfly"
     // Prints "Camel"
     // Prints "Dolphin"

但是在他的底层使用的是Array的迭代器遍历这个数组

     var animalIterator = animals.makeIterator()
     while let animal = animalIterator.next() {
         print(animal)
     }
     // Prints "Antelope"
     // Prints "Butterfly"
     // Prints "Camel"
     // Prints "Dolphin"

animals.makeIterator()返回当前数组的迭代器,下一步当while循环调用了迭代器的next()方法时,元素就被一个一个取出来了,直到next()返回nil的时候退出。

直接使用迭代器


  • 在通常的情况下我们直接使用for-in就可以满足,但是在某些场合下我们会直接使用迭代器。
  • 一个例子就是reduce1(_:)函数,类似于标准库中定义的reduce(_:_:)函数(带有一个初始值和一个结合闭包),reduce1(_:)需要用到序列的第一个元素作为初始值。
  • 下面就是reduce1(_:)的一个实现,直接使用迭代器来取初始值
extension Sequence {
         func reduce1(_ nextPartialResult: (Iterator.Element, Iterator.Element) -> Iterator.Element) -> Iterator.Element? {
             var i = makeIterator()
             guard var accumulated = i.next() else {
                return nil
             }
             while let element = i.next() {
                 accumulated = nextPartialResult(accumulated, element)
             }
             return accumulated
         }
     }

reduce1(_:)方法对于某些队列的操作更加简单,这里我们找出animals数组中最长的字符串:

    let longestAnimal = animals.reduce1 { current, element in
         if current.characters.count > element.characters.count {
             return current
         } else {
             return element
         }
     }
     // print(longestAnimal)
     // Prints "Butterfly"

使用多个迭代器


每当你在一个队列使用多个迭代器(或者for-in)时, 请确保特殊的队列能支持重复迭代,或者确保你知道他的具体类型,或者确保它遵守Collection协议。

从各自独立的迭代器到调用各自独立的迭代器的序列的makeIterator()方法,而不是通过复制。复制迭代器是安全的,但是调用复制后的迭代器的next()方法,就有可能会使其他这个迭代器的副本失效。for-in循环则是安全的
....

在自定义类型中合适的添加IteratorProtocol协议


实现一个合适迭代器很简单,定义一个next()函数,当前进一步的时候返回当前的元素,当这个序列结束,next()函数返回nil
例如,假设我们有个Countdown序列,你可以用一个起始数字初始化这个序列,然后迭代到0。这个数据结构定义的很短:它仅仅只有起始数和Sequence需要的makeIterator()方法。

struct Countdown: Sequence {
    let start: Int
    func makeIterator() -> CountdownIterator {
        return CountdownIterator(self)
    }
}

makeIterator()返回一个自定义迭代器CountdownIteratorCountdownIterator追踪Countdown序列的迭代和它返回值的次数

struct CountdownIterator: IteratorProtocol {
    let countdown: Countdown
    var times = 0
    
    init(_ countdown: Countdown) {
        self.countdown = countdown
    }
    
    mutating func next() -> Int? {
        let nextNumber = countdown.start - times
        guard nextNumber > 0
            else { return nil }
        
        times += 1
        return nextNumber
    }
}

每次next()方法是被当前CountdownIterator调用,他计算下一个新的数组,检查多久会减少到0,然后返回数字,或者在迭代器返回完序列的元素之后返回nil
调用:

 let threeTwoOne = Countdown(start: 3)
 for count in threeTwoOne {
    print("\(count)...")
}
// Prints "3..."
// Prints "2..."
// Prints "1..."

...

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 134,860评论 18 139
  • 一、基础知识:1、JVM、JRE和JDK的区别:JVM(Java Virtual Machine):java虚拟机...
    杀小贼阅读 2,404评论 0 4
  • Lua 5.1 参考手册 by Roberto Ierusalimschy, Luiz Henrique de F...
    苏黎九歌阅读 13,878评论 0 38
  • 我认真地行走在 绝望的边缘上 你却站在原点 冷眼旁观着我的流离 有时停留在你的肩膀上 可是永远都不能依靠 所以 我...
    柒忆阅读 307评论 2 4
  • 1、我妈和我爸是地地道道的农民,读过几年书,认识字而已。因为读书少,所以省吃俭用把我和妹妹供上大学。作为村里的第一...
    明媚朵朵阅读 360评论 2 0