Generator

Swift中,Generator是任何實現(xiàn)了GeneratorType協(xié)議的類或者結(jié)構(gòu)體。Generator可以理解為一個序列生成器。GeneratorType協(xié)議要求定義一個名為Element
的別名,并實現(xiàn)一個next
方法。
GeneratorType協(xié)議實現(xiàn)如下:

protocol GeneratorType{ 
    typealias Element 
    mutating func next()->Element?
}

語句typealias Element要求實現(xiàn)這個協(xié)議的類必須定義一個名為Element的別名,這樣一定程度上實現(xiàn)了泛型協(xié)議。協(xié)議同時要求實現(xiàn)next函數(shù),其返回值是別名中定義的Element類型,next函數(shù)代表生成器要生成的下一個元素。下面代碼實現(xiàn)了一個菲波那契數(shù)列生成器:

class FibonacciGenerator:GeneratorType{
    var current = 0, nextValue = 1 
    typealias Element = Int 
    func next() -> Element?{
        let ret = current 
        current = nextValue 
        nextValue = nextValue + ret 
        return ret 
    }
}

下面代碼打印出10個菲波那契數(shù)列,以顯示如何使用生成器:

var n = 10
var generator = FibonacciGenerator()
while n-- >0 {
    print(generator.next()!)
}

Generator是Sequence和Collection的基礎(chǔ)。

Sequence

Sequence是任何實現(xiàn)了SequenceType協(xié)議的類或者結(jié)構(gòu)體。Sequence可以理解為一個序列。SequenceType協(xié)議要求定義一個名為Generator,類型為GeneratorType的別名,并要求實現(xiàn)一個返回生成器Generator的函數(shù)。
SequenceType協(xié)議如下:

protocol SequenceType:_Sequence_Type{ 
    typealias Generator:GeneratorType 
    func generate()->Generator
}

類似于GeneratorType協(xié)議,typealias Generator : GeneratorType
要求實現(xiàn)這個協(xié)議的類必須定義一個名為Generator類型GeneratorType的別名。協(xié)議同時要求實現(xiàn)一個名為generate的函數(shù),其返回值為別名Generator定義的類型,這個類型應(yīng)該實現(xiàn)了上文提到的GeneratorType協(xié)議。也就是說Sequence其實是包含一個生成Generator的函數(shù)的類。
下面代碼使用上文中提到的菲波那契數(shù)列生成器,實現(xiàn)了一個菲波那契數(shù)列:

class FibonacciSequence:SequenceType{ 
    typealias GeneratorType = FibonacciGenerator 
    func generate() -> FibonacciGenerator{
        return FibonacciGenerator()
    }
}

下面代碼打印了10個菲波那契數(shù)列,以顯示如何使用該序列:

let fib = FibonacciSequence().generate()
for _ in 1..<10 { 
    print(fib.next()!)
}

符合SequenceType的序列有可能成為惰性序列。成為惰性序列的方法是對其顯示的調(diào)用lazy函數(shù):

let r = lazy(stride(from:1, to:8, by:2))

函數(shù)stride返回一個結(jié)構(gòu)體StrideTo,這個結(jié)構(gòu)體是Sequence。所以,lazy函數(shù)返回一個lazySequence對象。

Collection

Collection是實現(xiàn)了CollectionType協(xié)議的協(xié)議的類或者結(jié)構(gòu)體。CollectionType協(xié)議繼承了SequenceType協(xié)議。所以,Collection也都實現(xiàn)了SequenceType,它同時也是Sequence。
CollectionType協(xié)議如下:

protocol _CollectionType:_SequenceType{ 
    typealias Index:ForwardIndexType
    var startIndex:Index{get}
    var endIndex:Index{get} 
    typealias _Element 
    subscript (_i:Index)->_Element{get}
}
protocol CollectionType:_CollectionType,SequenceType{ 
    subscript (position:Self.Index)->Self.Generator.Element{get}
}

所以,CollectionType協(xié)議首先實現(xiàn)了SequenceType協(xié)議,并要求實現(xiàn)一個subscript方法以獲取序列中每個位置的元素值。
Swift中,大量內(nèi)置類如Dictionary,Array,Range,String都實現(xiàn)了CollectionType協(xié)議。所以,Swift大部分容器類都可以變?yōu)槎栊孕蛄小?/p>

// a will be a LazyRandomAccessCollection
// since arrays are random access
let a = lazy([1,2,3,4])
// s will be a LazyBidirectionalCollectionlet 
s = lazy("hello")

總結(jié)
Swift里的集合數(shù)據(jù)結(jié)構(gòu)默認是嚴格求值的。但是,Swift也提供了惰性語法,在需要惰性時,你需要顯式聲明。這為開發(fā)者在Swift中使用惰性提供了條件。

demo:


import Foundation  
  
// 先定義一個實現(xiàn)了 GeneratorType protocol 的類型  
// GeneratorType 需要指定一個 typealias Element  
// 以及提供一個返回 Element? 的方法 next()  
class ReverseGenerator: GeneratorType {  
    typealias Element = Int  
      
    var counter: Element  
    init<T>(array: [T]) {  
        self.counter = array.count - 1  
    }  
      
    init(start: Int) {  
        self.counter = start  
    }  
      
    func next() -> Element? {  
        return self.counter < 0 ? nil : counter--  
    }  
}  
  
// 然后我們來定義 SequenceType  
// 和 GeneratorType 很類似,不過換成指定一個 typealias Generator  
// 以及提供一個返回 Generator? 的方法 generate()  
struct ReverseSequence<T>: SequenceType {  
    var array: [T]  
      
    init (array: [T]) {  
        self.array = array  
    }  
      
    typealias Generator = ReverseGenerator  
    func generate() -> Generator {  
        return ReverseGenerator(array: array)  
    }  
}  
  
let arr = [0,1,2,3,4]  
  
/* 對 SequenceType 可以使用 for...in 來循環(huán)訪問.。 
for...in其實做了: 
var g = array.generate() 
while let obj = g.next() { 
print(obj) 
} 
*/  
for i in ReverseSequence(array: arr) {  
    print("Index \(i) is \(arr[i])")  
}  
/* 
像map , filter   reduce這些方法也可以使用 
因為SequenceType接口擴展(protocol extension)已經(jīng)實現(xiàn)了他們: 
extension SequenceType { 
    func map<T>(@noescape transform: (Self.Generator.Element) -> T) -> [T] 
    func filter(@noescape includeElement: (Self.Generator.Element) -> Bool) 
        -> [Self.Generator.Element] 
    @noescape combine: (T, Self.Generator.Element) -> T) -> T 
*/  
let aaa = ReverseSequence(array: arr)  
aaa.map { (Int) -> Int in  
    return 1  
}  

thx:http://ju.outofmemory.cn/entry/127998

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • 生成器(Generator)可以說是在 ES2015 中最為強悍的一個新特性,因為生成器是涉及到 ECMAScri...
    Will_Wen_Gunn閱讀 5,064評論 0 9
  • 簡介 基本概念 Generator函數(shù)是ES6提供的一種異步編程解決方案,語法行為與傳統(tǒng)函數(shù)完全不同。本章詳細介紹...
    呼呼哥閱讀 1,135評論 0 4
  • 官方中文版原文鏈接 感謝社區(qū)中各位的大力支持,譯者再次奉上一點點福利:阿里云產(chǎn)品券,享受所有官網(wǎng)優(yōu)惠,并抽取幸運大...
    HetfieldJoe閱讀 6,453評論 9 19
  • 在此處先列下本篇文章的主要內(nèi)容 簡介 next方法的參數(shù) for...of循環(huán) Generator.prototy...
    醉生夢死閱讀 1,486評論 3 8
  • 上一篇介紹了Promise異步編程,可以很好地回避回調(diào)地獄。但Promise的問題是,不管什么樣的異步操作,被Pr...
    張歆琳閱讀 1,546評論 0 13

友情鏈接更多精彩內(nèi)容