0
0
Swiftprogramming~20 mins

Async sequences (AsyncSequence) in Swift - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Async Sequence Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
What is the output of this async sequence code?
Consider the following Swift code using an async sequence. What will be printed when this code runs?
Swift
import Foundation

struct Countdown: AsyncSequence {
    typealias Element = Int
    let start: Int

    struct AsyncIterator: AsyncIteratorProtocol {
        var current: Int

        mutating func next() async -> Int? {
            if current < 0 {
                return nil
            } else {
                let value = current
                current -= 1
                return value
            }
        }
    }

    func makeAsyncIterator() -> AsyncIterator {
        AsyncIterator(current: start)
    }
}

@main
struct Main {
    static func main() async {
        let countdown = Countdown(start: 3)
        var result = ""
        for await number in countdown {
            result += "\(number) "
        }
        print(result.trimmingCharacters(in: .whitespaces))
    }
}
A"3 2 1 0 -1"
B"4 3 2 1 0"
C"0 1 2 3"
D"3 2 1 0"
Attempts:
2 left
💡 Hint
Think about how the iterator decreases the current value and when it stops.
🧠 Conceptual
intermediate
1:30remaining
Which statement about AsyncSequence is true?
Choose the correct statement about AsyncSequence in Swift.
AAsyncSequence allows iteration over values asynchronously using for await-in loops.
BAsyncSequence requires implementing a synchronous iterator method called makeIterator().
CAsyncSequence can only be used with arrays and dictionaries.
DAsyncSequence does not support throwing errors during iteration.
Attempts:
2 left
💡 Hint
Think about how async sequences are consumed in Swift.
🔧 Debug
advanced
2:00remaining
What error does this async sequence code produce?
This Swift code attempts to create an async sequence but has a problem. What error will it cause?
Swift
struct Numbers: AsyncSequence {
    typealias Element = Int

    func makeAsyncIterator() -> some AsyncIteratorProtocol {
        return Iterator()
    }

    struct Iterator: AsyncIteratorProtocol {
        var current = 0

        mutating func next() async -> Int? {
            if current < 3 {
                defer { current += 1 }
                return current
            } else {
                return nil
            }
        }
    }
}
ACompile-time error: 'current' used in mutating context but 'next()' is not mutating
BRuntime error: Infinite loop due to never returning nil
CCompile-time error: Missing async keyword on makeAsyncIterator()
DNo error, code runs correctly
Attempts:
2 left
💡 Hint
Check if the method that changes state is marked mutating.
📝 Syntax
advanced
1:30remaining
Which option correctly defines an async iterator's next() method?
Select the correct syntax for the next() method in an AsyncIteratorProtocol conforming struct.
Amutating func next() -> Element? async { ... }
Bfunc next() -> Element? async { ... }
Cmutating func next() async -> Element? { ... }
Dfunc next() async throws -> Element? { ... }
Attempts:
2 left
💡 Hint
Remember the order of async and throws keywords in Swift function declarations.
🚀 Application
expert
2:30remaining
How many items does this async sequence produce?
Given this async sequence, how many elements will be produced when iterated fully?
Swift
struct EvenNumbers: AsyncSequence {
    typealias Element = Int
    let max: Int

    struct Iterator: AsyncIteratorProtocol {
        var current = 0
        let max: Int

        mutating func next() async -> Int? {
            if current > max {
                return nil
            }
            let result = current
            current += 2
            return result
        }
    }

    func makeAsyncIterator() -> Iterator {
        Iterator(current: 0, max: max)
    }
}

@main
struct Main {
    static func main() async {
        let evens = EvenNumbers(max: 7)
        var count = 0
        for await _ in evens {
            count += 1
        }
        print(count)
    }
}
A5
B4
C7
D3
Attempts:
2 left
💡 Hint
Count even numbers from 0 up to and including max.