Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to make the class conform to the Sequence protocol.
Swift
class Countdown: Sequence { let start: Int init(start: Int) { self.start = start } func makeIterator() -> [1] { return CountdownIterator(current: start) } } class CountdownIterator: IteratorProtocol { var current: Int init(current: Int) { self.current = current } func next() -> Int? { if current <= 0 { return nil } else { defer { current -= 1 } return current } } }
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Returning the wrong type from makeIterator(), like Int or Sequence.
Forgetting to implement makeIterator() method.
✗ Incorrect
The makeIterator() method must return an instance of the iterator type, here CountdownIterator.
2fill in blank
mediumComplete the code to use the custom sequence in a for-in loop.
Swift
let countdown = Countdown(start: 3) for number in [1] { print(number) }
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Trying to iterate over the iterator directly instead of the sequence.
Calling makeIterator() explicitly in the for-in loop.
✗ Incorrect
You iterate over the instance of the Sequence, here 'countdown'.
3fill in blank
hardFix the error in the next() method to correctly stop iteration.
Swift
func next() -> Int? {
if current [1] 0 {
return nil
} else {
defer { current -= 1 }
return current
}
} Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using > or != causes the loop to never end or behave incorrectly.
Using == only stops at exactly zero, missing negative values.
✗ Incorrect
The iteration should stop when current is less than or equal to zero.
4fill in blank
hardFill both blanks to create a dictionary comprehension that maps numbers to their squares for numbers greater than 2.
Swift
let squares = Dictionary(uniqueKeysWithValues: (3...6).map { number in (number, number [1] number) }).filter { $0.key [2] 2 }
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using + instead of * for squaring.
Using < instead of > for filtering.
✗ Incorrect
Use * to square the number and > to filter numbers greater than 2.
5fill in blank
hardFill all three blanks to create a dictionary from a sequence where keys are strings uppercased and values are filtered to be greater than zero.
Swift
let data = ["a": 1, "b": -1, "c": 3] let filtered = data.reduce(into: [:]) { result, pair in let (key, value) = pair if value [1] 0 { result[[2]] = [3] } }
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using < instead of > for filtering.
Using key instead of key.uppercased() for dictionary keys.
Assigning key instead of value to the dictionary.
✗ Incorrect
Use > to filter positive values, uppercase the key for dictionary keys, and assign the value.