Created
April 19, 2020 04:51
-
-
Save myssun0325/6967cfd602a7fc2b3e46da0f7394a9b9 to your computer and use it in GitHub Desktop.
defer의 사용과 커스텀 Sequence 구현
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
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
내부적으로 CountDownIterator를 nested type으로 정의하기가 번거로우므로 사실상
CountDown자체가 IteratorProtocol을 준수하면
next()
만 구현해주면된다.