Swift
programming
generics
protocol-oriented
variable types

How to use generic protocol as a variable type

Object-Oriented Design practice on Codemia

Turn requirements into classes, and defend the design, on the problems that come up in OOD rounds.

Practice OOD

Introduction

In Swift, a protocol can describe behavior without naming a concrete type, but that does not mean every protocol can be stored directly in a variable. The main complication appears when the protocol includes an associatedtype or Self requirement, because the compiler then needs more type information than a plain variable declaration provides.

Why Some Protocols Cannot Stand Alone as Variable Types

Start with a protocol that has an associated type.

swift
1protocol Container {
2    associatedtype Item
3    mutating func append(_ item: Item)
4    var count: Int { get }
5}

This protocol is useful as a constraint, but Container by itself does not tell Swift what Item is. That missing information is why you cannot treat it like a fully concrete type in every situation.

The problem is not the word "protocol." The problem is that some operations only make sense when the associated type is known.

Use Generics When the Caller Can Stay Generic

If you only need to pass a conforming value into a function, generics are usually the best solution.

swift
1protocol Container {
2    associatedtype Item
3    var count: Int { get }
4}
5
6struct IntBox: Container {
7    let values: [Int]
8    var count: Int { values.count }
9}
10
11func printCount<C: Container>(_ container: C) {
12    print(container.count)
13}
14
15printCount(IntBox(values: [1, 2, 3]))

Here, C preserves the concrete conforming type, so Swift does not lose track of the associated type information.

This is the cleanest pattern when you do not need to store the value for later in a uniform container.

Use any for Existential Storage When It Fits

Swift uses the any keyword to make existential storage explicit.

swift
1protocol Named {
2    var name: String { get }
3}
4
5struct User: Named {
6    let name: String
7}
8
9let value: any Named = User(name: "Ava")
10print(value.name)

That works because Named does not depend on an unresolved associated type for the operation you are performing.

The key point is that any does not erase type-system rules. It only says, "store a value that conforms to this protocol as an existential." If the protocol requirements depend on hidden type information, you still may not be able to use it the way you expect.

Use Type Erasure When You Need One Concrete Wrapper

When you must store protocol-conforming values behind one concrete type, type erasure is the standard approach.

swift
1protocol Producer {
2    associatedtype Output
3    func produce() -> Output
4}
5
6struct IntProducer: Producer {
7    func produce() -> Int { 42 }
8}
9
10struct AnyIntProducer: Producer {
11    typealias Output = Int
12
13    private let _produce: () -> Int
14
15    init<P: Producer>(_ base: P) where P.Output == Int {
16        _produce = base.produce
17    }
18
19    func produce() -> Int {
20        _produce()
21    }
22}
23
24let producer = AnyIntProducer(IntProducer())
25print(producer.produce())

The wrapper fixes the associated type to something known, in this case Int, and forwards calls to the hidden concrete implementation.

Type erasure is more code, so it is worth using only when you actually need storage abstraction rather than simple generic passing.

Decide Based on the Operation You Need

A useful rule is:

  • use generics when the code can remain generic end to end
  • use any ProtocolName when existential storage is valid for the operations you need
  • use type erasure when you need one concrete wrapper around values that share a compatible associated type

That decision is driven by compiler requirements, not personal style.

For example, if you need a collection of values that all produce Int, a type-erased wrapper can work well. If each value produces a different output type, one wrapper may not be enough because the shared associated type requirement disappears.

Common Pitfalls

The biggest mistake is assuming every protocol can be used like a class name in a variable declaration.

Another mistake is expecting any to solve all protocol-with-associated-type problems automatically. It makes the existential explicit, but it does not invent the missing type information.

A third issue is reaching for type erasure too early. If a generic function solves the problem, it is usually clearer and cheaper than building a wrapper type.

Finally, if you plan to store several conforming values together, verify that the associated types actually line up. If they do not, you are trying to unify values that the type system sees as fundamentally different.

Summary

  • A protocol with an associatedtype or Self requirement is not always usable as a plain variable type.
  • Generics are the simplest solution when the surrounding code can remain generic.
  • 'any Protocol works for existential storage only when the required operations still make sense without hidden type details.'
  • Type erasure gives you a concrete wrapper when you need storage abstraction.
  • Choose the approach based on what type information must stay available.
  • In Swift, this is a modeling problem, not just a syntax issue.

Course
Intermediate
27 lessons
14 hours
OOD Fundamentals

Master object-oriented design from first principles, SOLID, design patterns, and classic interview problems with hands-on coding.

View the course
Object-Oriented Design practice on Codemia

Turn requirements into classes, and defend the design, on the problems that come up in OOD rounds.

Practice OOD