0Pricing
Swift Academy · Lesson

Choosing between some, any, and generics

Pick generics for homogeneous static typing, some P to hide a fixed concrete type, and any P for heterogeneous polymorphism.

Choosing between some, any, and generics is a free Swift Academy lesson on CoddyKit — lesson 3 of 3. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Swift Academy learning path, one of 3 lessons in the course, and your progress syncs across the web and the CoddyKit app.

When to use which?

Rule of thumb:

  • Generics: same concrete type per call; best compile-time checks & performance.
  • some P: hide the concrete return type, fixed per function.
  • any P: mix conformers (heterogeneous), dynamic dispatch.

Generics: homogeneous

Generics are ideal for homogeneous data and optimization (static dispatch, inlining).

protocol Shape { func area() -> Double }

struct Circle: Shape { let r: Double; func area() -> Double { .pi * r * r } }
struct Square: Shape { let s: Double; func area() -> Double { s * s } }

// Generic: one concrete Shape type per call site (homogeneous)
func totalAreaGeneric<S: Sequence, T: Shape>(_ xs: S) -> Double where S.Element == T {
    xs.reduce(0) { $0 + $1.area() }
}
print(totalAreaGeneric([Circle(r:1), Circle(r:2)]))  // OK
// totalAreaGeneric([Circle(r:1), Square(s:2)])      // ❌ different types

Opaque: hide but fixed

some P returns a fixed but hidden type. Great when you want encapsulation without losing static performance.

// Opaque factory hides the concrete type while guaranteeing Shape
func unitShape(flag: Bool) -> some Shape {
    // Must return the SAME underlying type on all paths; pick one.
    Circle(r: 1)
}
let s = unitShape(flag: true)
print(String(format: "%.2f", s.area()))  // 3.14

any P: heterogeneous

any P allows mixed types in one collection or variable; methods dispatch dynamically via the protocol interface.

// Existential: store mixed conformers
let mixed: [any Shape] = [Circle(r: 1), Square(s: 2)]
let sum = mixed.reduce(0) { $0 + $1.area() }   // dynamic dispatch
print(String(format: "%.2f", sum))

API shapes compared

Pick the surface:

  • Generic: caller controls concrete type.
  • Opaque: you hide the type, fixed per function.
  • Existential: you may vary concrete types dynamically.
// Three API shapes for the same idea: "make a Shape"

// 1) Generic return — exposes concrete type to caller
func makeGeneric<T: Shape>(_ t: T) -> T { t }

// 2) Opaque return — hides concrete type but fixed
func makeOpaqueCircle() -> some Shape { Circle(r: 1) }

// 3) Existential return — can return any conformer
func makeExistential(_ big: Bool) -> any Shape { big ? Square(s: 3) : Circle(r: 1) }

let g: Circle = makeGeneric(Circle(r: 2))      // caller knows concrete type
let o = makeOpaqueCircle()                      // caller sees only Shape
let e = makeExistential(true)                   // could be Circle or Square at runtime
print(g.area(), o.area(), e.area())

Cheat sheet

Guidelines:

  • Prefer generics for performance and strong typing when data is homogeneous.
  • Use some P to hide return types and keep APIs stable.
  • Use any P for plugin-like or mixed collections.
  • Avoid any P for protocols with associated types/Self unless you type-erase.

Decision check: choose some/any/generics

Quick check: Which option hides a fixed concrete return type behind protocol P?

Recap

Recap:

  • Generics = homogeneous, fastest, most static.
  • some P = hide concrete type, fixed per function.
  • any P = heterogeneous, dynamic dispatch.

Frequently asked questions

Is the “Choosing between some, any, and generics” lesson free?

Yes — the full text of “Choosing between some, any, and generics” is free to read here on the web, and the Swift Academy course includes 3 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Swift Academy course, upgrade to CoddyKit PRO.

What will I learn in “Choosing between some, any, and generics”?

Pick generics for homogeneous static typing, some P to hide a fixed concrete type, and any P for heterogeneous polymorphism. You practise Swift Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.

Do I need any experience to start Swift Academy?

No prior experience is required. Swift Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 3 of 3, so you can start here or from the beginning and move at your own pace.

How long does the “Choosing between some, any, and generics” lesson take?

Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.

Can I write and run code in this Swift Academy lesson?

Yes. Every Swift Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.

All lessons in this course

  1. some P (opaque result types): hiding concrete types
  2. any P (existential): trade-offs & dynamic dispatch
  3. Choosing between some, any, and generics
← Back to Swift Academy