Generics

Swift language Junior Swift 5.0+ iOS 17+ Reviewed By Alok Singh

Pick the fix

You need largest for an array of any comparable element type. Which signature?

Options
Hint 1 of 1

Which option keeps one concrete element type?

Choose an answer, then open Show answer below to check it.

Show answer

Answer: A func largest<T: Comparable>(_ xs: [T]) -> T?

Correct. One implementation, type-safe, specialized per type.

Why not the others?
  • B func largest(_ xs: [Any]) -> Any?. Any can't be compared without casting.
  • C func largest(_ xs: [any Comparable]) -> (any Comparable)?. Two existentials may hold different types, so you can't compare them directly.
  • D Separate overloads for Int, Double and String. Duplicated code that misses every other Comparable type.

30-second answer

Generics let you write one function or type that works with many types while keeping full type safety. Constraints (T: Comparable) say what the type must support. The compiler can specialize generic code for each concrete type, so you keep performance without duplicating code or falling back to Any.

Practise saying it · 30 s. No recording, just a timer

Explain generics and constraints.

Say your answer out loud, then check which of these points you covered:

  • One implementation for many types
  • Constraints
  • Specialization keeps performance

Deep dive

where clauses add constraints, for example where T.Element: Hashable.

some Protocol in parameter position is shorthand for a generic parameter.

Generic types: struct Stack<Element>.

Swift 5.9 added parameter packs for variadic generics.

Common mistakes

  • Using Any and casting instead of generics.
  • Writing overloads per type.

Senior take & follow-ups

Seniors discuss specialization and when an existential is the simpler choice.

Follow-up questions

Think of your answer first, then open the hint.

  1. What's the difference between func f<T: P>(_ x: T) and func f(_ x: any P)?

    Show hint

    Static type and specialization versus a boxed existential.

  2. What are parameter packs for?

    Show hint

    Functions over any number of types, like zip for N sequences.

Suggest a fix if something here is wrong or out of date.