Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save biloshkurskyi-ss/d9ef9005e64667add91e0c004d48fcf6 to your computer and use it in GitHub Desktop.
Save biloshkurskyi-ss/d9ef9005e64667add91e0c004d48fcf6 to your computer and use it in GitHub Desktop.
Sequences with IteratorProtocol examples
import Foundation
// MARK: - Sequences
struct ConstantIterator: IteratorProtocol {
typealias Element = Int
mutating func next() -> Element? {
return 1
}
}
//Example from infinity of 1
//var iterator = ConstantIterator()
//while let x = iterator.next() {
// print(x)
//}
struct FibsIterator: IteratorProtocol {
var state = (0,1)
mutating func next() -> Int? {
let upcomingNumber = state.1
state = (state.1, state.0 + state.1)
return upcomingNumber
}
}
//Example from 1 to Int.max
//var iterator = FibsIterator()
//while let x = iterator.next() {
// print(x)
//}
struct FibSequence: Sequence {
func makeIterator() -> FibsIterator {
return FibsIterator()
}
}
//Example from 1 to prefix element
for i in FibSequence().prefix(10) {
print(i)
}
//1,1,2,3,5,8,13,21,34,55
struct PrefixIterator: IteratorProtocol {
typealias Element = Substring
let string: String
var offset: String.Index
init(string: String) {
self.string = string
offset = string.startIndex
}
mutating func next() -> Element? {
guard offset < string.endIndex else { return nil }
offset = string.index(after: offset)
return string[..<offset]
}
}
struct PrefixSequence: Sequence {
let string: String
func makeIterator() -> PrefixIterator {
return PrefixIterator(string: string)
}
}
// Example of string slising
for prefix in PrefixSequence(string: "Hello") {
print(prefix)
}
//H,He,Hel,Hell,Hello
// Example of mapping
print(PrefixSequence(string: "Hello").map { $0.uppercased() })
//["H", "HE", "HEL", "HELL", "HELLO"]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment