Swift 中的 SquenceType

swift 中很好用的for循環(huán)語句for...in.它的實現(xiàn)原理是需要遵循SequenceType,且要縣遵循GenreatorType 先看下面例子

//先定義一個實現(xiàn)了 GenreatorType Protocol的類型

`class TestList: SequenceType {

    private var testList:[Test]?
    init() {
        self.testList = [Test]()
    }
    
    func addTest(test:test){
        self.testList?.append(book)
    }
    
    typealias Generator = BookListGenerator
    
    func generate() -> Generator {
        
        return testListGenerator(bookList: self.bookList!)
        
    }

}`

class test {

    var name:String = ""
    init(name: String) {   
        self.name = name  
    }

}

class TestListGenerator : GeneratorType {}

    typealias Element = Book

    var currentIndex:Int = 0
    var testList:[Test]?
    
    init(testList: [Test]) {
        self.testList = bookList 
    }
    
    func next() -> Element? {
        
        guard let list = testList else { return  nil }
        
        if currentIndex < list.count {
            
            let element = list[currentIndex]
            currentIndex += 1
            return element
            
        }else {
            
            return nil
            
        }
    }

}

let testList = testList()

testList.addTest(Test(name: "Swift"))

testList.addTest(Test(name: "iOS" ))

for test in testList {

    print("\(test.name)")

}
  • 看了上述的例子,大致可以自定義一個可以for...in的對象了
  • 更驚喜的是我不還可以使用想數(shù)組的map\filter、reduce方法,這因為SquenceType已經(jīng)擴展實現(xiàn)了它們
最后編輯于
?著作權(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)容

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