Skip to content
Tutorials Center
My learning

Topics

Lesson 146 of 146 ยท Practice

Practice Problems: Protocols and Generics

Ten Swift exercises on protocols, extensions, generics, associated types, conditional conformance and opaque types, each with a hint and a runnable, explained solution.

Protocols and generics are where Swift code stops looking like code from other languages. They are also where beginners get stuck: error messages mention "associated types" and "Self requirements", and it is not obvious which tool to pick. The only cure is practice.

This lesson has ten exercises. Each has a task, a hint and a runnable solution with a short explanation of the design choice. Try to solve the task yourself before you open the solution. If you need to refresh a topic first, read protocols, protocol extensions, generics, associated types, conditional conformance and opaque types.

flowchart TD
    Q["I need to write code that works with<br/>several types"] --> A{"Do the types share<br/>a class hierarchy?"}
    A -->|"yes, and I need shared state"| C["Class inheritance"]
    A -->|"no"| B{"Same behavior for<br/>every type?"}
    B -->|"yes"| G["Generic function or type<br/>with constraints"]
    B -->|"no, each type does it differently"| P["Protocol requirement<br/>+ default in an extension"]
    P --> H{"Need a mixed collection<br/>at runtime?"}
    H -->|"yes"| E["any Protocol"]
    H -->|"no"| S["some Protocol or generic T"]

A rough decision guide for choosing between inheritance, generics, protocols, any and some.

Protocols and extensions

Exercise 1: A protocol with a default implementation

Define a protocol Describable with a name: String property and a describe() method. Give describe() a default implementation, then make a type that uses the default and a type that overrides it.

Hint: a method declared in the protocol and in the extension is dispatched dynamically, so a conforming type's own version wins.

Exercise 2: Protocol with a static requirement

Define Identified with static var prefix: String and var number: Int. Add an extension that provides var tag: String, for example "ORD-17".

Hint: inside the extension, Self.prefix reads the conforming type's static value.

Swift Solutions 1 and 2

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

Because describe() is a protocol requirement, calling it on an any Describable runs Fancy's version. If you had put describe() only in the extension (not in the protocol), the call through any Describable would always use the extension's version. That surprise is a classic interview question.

Generic functions

Exercise 3: A generic largest(in:)

Write a function returning the largest element of any collection of comparable values, or nil if it is empty. It should work on arrays, sets and ranges alike.

Hint: constrain a generic C: Collection where C.Element: Comparable.

Exercise 4: Generic grouping

Write group(_:by:) that takes any sequence and a key function and returns a dictionary from key to the elements with that key, in original order.

Hint: the key type must be Hashable. Use default: [] while appending.

Swift Solutions 3 and 4

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

Notice what the signatures promise: largest works for any collection, not only arrays, and returns an element of that collection. The compiler specializes each call, so there is no runtime cost for the flexibility (see Performance Tips).

Associated types and generic types

Exercise 5: A Stack protocol and two implementations

Define a protocol Stack with an associated type Element, push, pop and peek. Implement it with a struct backed by an array. Then write one generic function that drains any stack into an array.

Hint: protocol Stack { associatedtype Element ... } and func drain<S: Stack>(_ s: inout S) -> [S.Element].

Exercise 6: A generic Cache with a size limit

Create LRUCache<Key: Hashable, Value> with a capacity. get marks an entry as recently used; inserting beyond capacity evicts the least recently used entry.

Hint: an array of keys ordered from oldest to newest plus a dictionary of values is enough for an exercise.

Swift Solutions 5 and 6

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

ArrayStack could be replaced by a linked-list stack and drain would not change; that is the point of programming against the protocol. The cache is O(n) per access because of removeAll. A production version uses a doubly linked list (see deque and heap ideas); say so in an interview.

Conditional conformance and extensions

Exercise 7: Conditional Equatable-style conformance for your own wrapper

Create a generic Box<T>. Make it Equatable only when T is Equatable, and give it an isEmpty property only when T is a String.

Hint: extension Box: Equatable where T: Equatable {} and extension Box where T == String { ... }.

Exercise 8: Add average to numeric collections

Add an average() method to every Collection whose elements are BinaryInteger, returning Double?, and a second one for BinaryFloatingPoint.

Hint: convert with Double(exactly:) or Double($0); return nil for an empty collection.

Swift Solutions 7 and 8

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

The rule behind both: an extension with a where clause adds API only when the clause holds. It is how Array is Equatable only when its elements are, and why [1, 2] == [1, 2] compiles while an array of closures cannot be compared.

Opaque and existential types

Exercise 9: Return some, store any

Write a protocol Shape with area and a function makeUnitSquare() that returns some Shape. Then build a [any Shape] of different shapes and print the total area.

Hint: some hides one concrete type that the compiler still knows; any allows different types in one array at the cost of dynamic dispatch.

Exercise 10: A type-erased closure wrapper

Write a generic Validator<Value> struct that wraps a closure (Value) -> Bool, has a && operator to combine validators, and a static factory Validator.minLength(_:) for strings.

Hint: a struct holding a closure is the simplest type erasure: callers never see the concrete implementation.

Swift Solutions 9 and 10

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

The wrapper hides how each check is built, yet the combined password has the same type as its parts, so validators compose like building blocks.

Common traps

  • Using any when a generic is enough. func total(_ items: [any Shape]) boxes every element. func total<S: Shape>(_ items: [S]) does not, but only accepts one concrete type per call.
  • Forgetting that protocol extension methods not in the protocol are statically dispatched. Add them to the protocol if conforming types should be able to override them.
  • Constraining too tightly. Asking for Array<Int> where some Sequence<Int> would do blocks sets, ranges and lazy sequences.
  • Reaching for a class hierarchy first. Prefer a protocol and structs unless you really need shared identity or inherited stored state.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. A method is declared only in a protocol extension, not in the protocol itself. A type conforms and defines its own version. What runs when you call it through an any existential?

    Without a protocol requirement there is no witness table entry, so the call is bound statically to the extension's implementation. Declare the method in the protocol to allow overriding.
  2. 2. What does extension Box: Equatable where T: Equatable {} do?

    This is conditional conformance. The synthesized == compares the stored value, so it requires T to be Equatable.
  3. 3. Which signature accepts arrays, sets and ranges?

    Constraining a generic parameter to Collection with Comparable elements accepts every collection type and returns the same element type.
  4. 4. When should you choose any Shape over some Shape or a generic?

    any allows values of different concrete types behind one type at the cost of boxing and dynamic dispatch. If one concrete type is enough, some or a generic is cheaper.
  5. 5. Why does the LRU cache in Exercise 6 cost O(n) per access?

    removeAll scans the order array and append may shift elements. A doubly linked list plus a dictionary of nodes gives O(1).

Summary

  • Put behavior in a protocol, share defaults in an extension, and declare anything overridable as a requirement.
  • Use generics with constraints (where clauses) to write one function for many types without runtime cost.
  • Associated types let a protocol describe "an element type" that each conformer picks; generic functions then name it as S.Element.
  • Conditional conformance and constrained extensions add API only when the constraint holds.
  • Use some for one hidden concrete type, any for heterogeneous storage, and a struct that wraps a closure for simple type erasure.
  • Say the trade-offs aloud: dispatch cost, flexibility and what the compiler can prove.

Next: Swift Cheat Sheet