Sequenceというプロトコルを試してみました。
Sequenceは配列に使われているプロトコルで、準拠することでforEachやmapなどのメソッドを使うことができます。
実装例は下の通りです。
deferを使ってreturnの後にcountを-1しています。
これで10から1までを順番に取り出せる構造体を作ることができました。
struct Countdown: Sequence, IteratorProtocol { var count: Int mutating func next() -> Int? { if count == 0 { return nil } else { defer { count -= 1 } return count } } } Countdown(count: 10).forEach { print($0) } // → 10, 9, 8...2, 1
サンプルは下URLのものを使っています。
https://developer.apple.com/documentation/swift/sequence
下のようにInt以外を扱うことも可能です。
struct MySequence: Sequence, IteratorProtocol { var index = 0 let texts = ["a", "b", "c", "d", "e"] mutating func next() -> String? { if index >= texts.count { return nil } else { defer { index += 1 } return texts[index] } } } MySequence().forEach { print($0) } // → "a", "b", "c", "d", "e"