0
0
Swiftprogramming~30 mins

Sequence protocol for custom iteration in Swift - Mini Project: Build & Apply

Choose your learning style9 modes available
Sequence protocol for custom iteration
📖 Scenario: Imagine you have a collection of daily temperatures and you want to create a custom way to go through them one by one.
🎯 Goal: You will build a custom type that holds a list of temperatures and lets you iterate over them using Swift's Sequence protocol.
📋 What You'll Learn
Create a struct called TemperatureLog that stores an array of Int temperatures
Add a property called temperatures with the exact values [72, 75, 79, 80, 68]
Create a struct called TemperatureIterator that conforms to IteratorProtocol
Implement the next() method in TemperatureIterator to return the next temperature
Make TemperatureLog conform to Sequence by implementing the makeIterator() method
Print each temperature from TemperatureLog using a for loop
💡 Why This Matters
🌍 Real World
Custom sequences let you control how data is accessed step-by-step, useful for processing logs, sensor data, or any list where you want special rules for moving through items.
💼 Career
Understanding how to create custom sequences and iterators is important for Swift developers working on apps that handle streams of data, animations, or complex collections.
Progress0 / 4 steps
1
Create the TemperatureLog struct with temperatures
Create a struct called TemperatureLog with a property temperatures set to the array [72, 75, 79, 80, 68].
Swift
Need a hint?

Use struct TemperatureLog { let temperatures = [72, 75, 79, 80, 68] } to create the data container.

2
Create TemperatureIterator struct conforming to IteratorProtocol
Create a struct called TemperatureIterator that conforms to IteratorProtocol. Add a property temperatures of type [Int] and an index property currentIndex initialized to 0.
Swift
Need a hint?

Define struct TemperatureIterator: IteratorProtocol with the properties temperatures and currentIndex.

3
Implement next() method in TemperatureIterator
Inside TemperatureIterator, implement the next() method that returns the next temperature from temperatures or nil if at the end. Increase currentIndex after returning a value.
Swift
Need a hint?

Use mutating func next() -> Int? and check if currentIndex is less than the array count to return the next temperature.

4
Make TemperatureLog conform to Sequence and print temperatures
Make TemperatureLog conform to Sequence by adding a makeIterator() method that returns a TemperatureIterator initialized with temperatures. Then, use a for loop to print each temperature from an instance of TemperatureLog.
Swift
Need a hint?

Implement func makeIterator() -> TemperatureIterator returning TemperatureIterator(temperatures: temperatures). Then use for temp in log { print(temp) }.