DevPrep

All topics › Real interview tasks

A FIFO request queue with type erasure (any / some)

Senior PRO

Task

You have a protocol with associated types. Write a queue that runs requests strictly one at a time, in insertion order. add must accept any Request.

protocol Request {
    associatedtype Response
    associatedtype Failure: Error

    typealias Handler = (Result<Response, Failure>) -> Void

    var handler: Handler { get }
    func perform(then handler: @escaping Handler)
}

final class RequestQueue {
    func add(_ request: Request) { } // doesn't compile — why?
}

The rest of this answer, with code and interview follow-ups, is in the DevPrep app.

Read the full answer in DevPrep

Practice this before your interview

DevPrep turns these answers into one-minute challenges: what does this code print, find the bug, mock interviews. One challenge a day.

Get DevPrep on the App Store