How do you implement and use custom protocols with associated types in Swift?

Instruction: Provide an example of defining a custom protocol with an associated type, and a class or struct that conforms to it.

Context: This question evaluates the candidate’s ability to work with advanced Swift features like protocols with associated types, showcasing their understanding of generic programming paradigms.

Updated

Official answer

An associated type is a placeholder in a protocol whose concrete type is chosen by each conforming type. A generic caller can preserve that relationship rather than erasing the returned value to Any.

This complete synchronous fixture returns a stored model; it does not make a network request:

protocol DataProvider {
    associatedtype Model
    func fetch() -> Model
}
struct User: Equatable { let name: String }
struct UserProvider: DataProvider {
    typealias Model = User
    let user: User
    func fetch() -> User { user }
}
func load<P: DataProvider>(_ provider: P) -> P.Model {
    provider.fetch()
}
let provider = UserProvider(user: User(name: "Jane"))
let user: User = load(provider)
assert(user == User(name: "Jane"))

Swift can infer Model from the matching fetch signature, so the explicit typealias is explanatory rather than mandatory. A second provider can choose a different Model while reusing load. Use a same-type constraint when a caller specifically requires a User model.

Modern Swift supports existential values written with any, including protocols with associated types, but the operations and type relationships available through an existential depend on its constraints. It is incorrect to claim these protocols can never be used as types. Generics are useful here because the caller retains the provider's concrete Model relationship.

For a real asynchronous data source, design its async/throws and cancellation contract separately. Protocol conformance checks the required signatures; it does not prove that a provider is correct, fast or safe to share across concurrency domains.

Swift generics and associated types

Related Questions