迭代器

迭代器(Interator)这个概念你可能不陌生,但是解释起来又觉得含糊不清

Swift的标准库中大量的使用了迭代器设计模式

希望下面这点内容能够给你带来一点点作用

迭代器模式让你能够迭代一个合集里的元素;迭代器为你提供一个方法,让你访问容器对象中的各个元素,而又不暴露该对象的内部细节。

import UIKit

// 字符串迭代器

protocol StringInterator {

    func next() -> String?

}

class ArrayStringInterator: StringInterator {

    private let values: [String]

    private var index: Int?

    init(_ values: [String]) {

        self.values = values

    }

    private func nextIndex(for index:Int?) -> Int? {

        if let index = index,index < self.values.count - 1 {

            return index + 1

        }

        if index == nil, !self.values.isEmpty {

            return 0

        }

        return nil

    }

    func next() -> String? {

        if let index = self.nextIndex(for: self.index) {

            self.index = index

            return self.values[index]

        }

        return nil

    }

}

protocol Iterator {

    func makeInterator() -> StringInterator

}

class DataArray: Iterator {    

    private var dataSource: [String]

    init() {

        self.dataSource = [" "," "," "," "," "," "," ",]

    }

    func makeInterator() -> StringInterator {

        return ArrayStringInterator(self.dataSource)

    }

}

let data = DataArray()

let iterator = data.makeInterator()

while let next = iterator.next() {

    print(next)

}

 

swift有自建的自定义序列Sequence,帮助创建迭代器。实现自己的序列实际上就是通过自定义迭代器隐藏函数的内部的数据结构体。

比序列Sequence更强大的是Collection(Sequence -> Collection)

Swift 提供来三种集合类型,即Array、Set、Dictionary。Array是值的有序集合;Set是无重复值的无序集合;Dictionary是键值对的无序集合

一个Collection是满足下面条件的Sequence

1、稳定的Sequence,能够被多次遍历且保持一致

2、除了线性遍历以外,集合中的元素可以通过下标索引的方式被获取到

3、和Sequence不同,Collection类型不能是无限的

 

 

 

 

 

 

 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值