0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

【Swift】SequenceとIteratorProtocolでfor-inですべてのデータを取り出すサンプル

Last updated at Posted at 2020-02-11

SequenceとIteratorProtocolを使ってfor-inですべてのデータを取り出す書き方のサンプルです。

SequenceとIteratorProtocolのサンプル
class T {
    var n = 1;
    init(_ n: Int) {
        self.n = n
    }
}

class C: Sequence, IteratorProtocol {
    typealias Element = T
    var ta = [T](repeating: T(1), count: 100)
    var i = 0
    
    func next() -> T? {
        guard i < ta.count else {
            i = 0
            return nil
        }
        let r = ta[i]
        i += 1
        return r
    }
}

var c = C()
for e in c {
    print(e.n)
}
0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?