Pebble Coding

ソフトウェアエンジニアによるIT技術、数学の備忘録

swift3 Collectionプロトコル

Collectionプロトコルを作るには、
startIndexプロパティ,endIndexプロパティ,subscript,index(after:) の4つを実装する必要がある。
Collection - Swift Standard Library | Apple Developer Documentation

ここでは奇数を返すコレクションOddを作ってみた。

struct Odd : Collection {
    var startIndex: Int
    var endIndex: Int
    subscript(i: Int) -> Int {
        return 1 + 2 * i  
    }
    func index(after: Int) -> Int {
        return after + 1
    }
}

let odd = Odd(startIndex:1, endIndex:4)
for i in odd {
    print("\(i)")
}
3
5
7