What if you could make your own collections that just work with Swift's loops, no extra hassle?
Why Sequence protocol for custom iteration in Swift? - Purpose & Use Cases
Imagine you have a list of items and you want to go through each one, but the way you want to go through them is special -- maybe skipping some, or combining steps. Doing this by hand means writing lots of loops and checks everywhere.
Manually writing loops for every special way to go through items is slow and tiring. It's easy to make mistakes, forget to update all loops if the rules change, and your code becomes messy and hard to read.
The Sequence protocol lets you define exactly how to go through your items once, in one place. Then you can use simple loops everywhere else, and your special rules happen automatically and cleanly.
var i = 0 while i < items.count { if shouldInclude(items[i]) { print(items[i]) } i += 1 }
struct CustomSequence: Sequence {
func makeIterator() -> some IteratorProtocol {
// custom iterator logic here
return CustomIterator()
}
}
struct CustomIterator: IteratorProtocol {
mutating func next() -> ItemType? {
// custom iteration logic here
}
}
for item in CustomSequence() {
print(item)
}You can create your own easy-to-use collections that work naturally with Swift's powerful loops and functions.
Think of a music playlist app that skips songs you dislike automatically when you play through the list. Using Sequence, the app can handle this skipping inside the playlist itself, so the player just plays songs one by one without extra checks.
Manual loops for custom steps are slow and error-prone.
Sequence protocol lets you define iteration once, cleanly.
Use simple loops everywhere else with your custom rules built-in.