Skip to content

Instantly share code, notes, and snippets.

@myssun0325
Created April 19, 2020 04:51
Show Gist options
  • Save myssun0325/6967cfd602a7fc2b3e46da0f7394a9b9 to your computer and use it in GitHub Desktop.
Save myssun0325/6967cfd602a7fc2b3e46da0f7394a9b9 to your computer and use it in GitHub Desktop.
defer의 사용과 커스텀 Sequence 구현
struct CountDown: Sequence {
var value: Int
struct CountDownIterator: IteratorProtocol {
var value: Int
mutating func next() -> Int ? {
if value < 0 { return nil }
defer{ value -= 1} // 여기서 사용되는 defer
return value
}
}
func makeIterator() -> CountDownIterator {
return CountDownIterator(value: self.value)
}
}
for i in CountDown(value: 5) {
print(i)
}
// 5, 4, 3, 2, 1, 0
@myssun0325
Copy link
Author

내부적으로 CountDownIterator를 nested type으로 정의하기가 번거로우므로 사실상
CountDown자체가 IteratorProtocol을 준수하면 next()만 구현해주면된다.

@myssun0325
Copy link
Author

struct SimpleCount: Sequence, IteratorProtocol {
  var value: Int
  mutating func next() -> Int? {
    if value < 0 { return nil }
    value -= 1
    return value + 1
  }
}

// usage
for i in SimpleCountDown(5) { print(i) }

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment