Chapter 70: Swift Collection Protocols

1. Why does Swift have Collection Protocols? (the most important big picture)

Swift wants to let you write generic, reusable code that works with many different kinds of collections — not just Array.

Examples of different kinds of collections:

  • Array – ordered, allows duplicates
  • Set – unordered, no duplicates
  • Dictionary – key-value pairs (keys are unique)
  • String – sequence of characters
  • ArraySlice – view into part of an array
  • Custom collections you write yourself
  • Third-party types (e.g. from libraries)

Instead of writing separate functions for each type:

Swift

Swift lets you write one generic function that works with all of them — as long as they conform to the right protocol.

That is the whole reason for Collection protocols.

2. The Main Collection Protocols – Hierarchy Overview

Here is the most important family tree you should keep in mind:

text

You will mostly interact with these four:

Protocol Ordered? Index type Random access? Typical types that conform When you care about it
Sequence Yes — (no index) No Array, Set, Dictionary, String, Range, StrideThrough… When you just iterate (for-in, forEach, map, filter…)
Collection Yes Index (opaque) No (but fast in practice for Array) Array, Set, Dictionary, String, ArraySlice… When you need .count, .isEmpty, subscript [index], .first, .last…
BidirectionalCollection Yes Supports going backward No Array, Set, Dictionary, String… When you need .last, .reversed(), iterate backward
RandomAccessCollection Yes Supports fast jumping Yes Array, ArraySlice, ContiguousArray, Range… When you need fast random access coll[i] or slicing

Rule of thumb used by most good Swift developers:

  • If you only iterate (for-in, map, filter, reduce, forEach) → Sequence is enough
  • If you need count, subscript, first/last → you usually want Collection
  • If you need fast random access or slicing → RandomAccessCollection (Array is this)

3. Sequence – the foundation (what almost everything conforms to)

Swift

Real-life use-case – generic logging function

Swift

4. Collection – when you need count, indices, subscript

Swift

This function works with Array, Set, Dictionary.keys, String, ArraySlice, etc.

Real-life example – safe slicing / pagination

Swift

5. RandomAccessCollection – when you need fast random access

Swift
Swift

Array, ArraySlice, ContiguousArray conform to RandomAccessCollection. Set and Dictionary do not — their access is fast but not guaranteed O(1) for indexed access.

6. Real-life examples you will actually write

Example 1 – Generic function that works on any Collection

Swift

This one function works with Array, Set, Dictionary.keys, String, etc.

Example 2 – Safe pagination / slicing

Swift

7. Quick Summary – Which protocol should you usually ask for?

You need… Minimum protocol you should ask for Why? / Typical generic signature
Just iterate (for-in, forEach, map, filter) Sequence func process<S: Sequence>(_ items: S) where S.Element == String
Need .count, .isEmpty, .first, .last, subscript Collection func summary<C: Collection>(_ items: C)
Need fast random access / slicing RandomAccessCollection func swapFirstLast<C: RandomAccessCollection & MutableCollection>(_ c: inout C)
Need bidirectional walking (rare) BidirectionalCollection reversed(), backward iteration

Rule of thumb used by most good Swift developers:

  • Start with Sequence — it’s the most flexible
  • Move to Collection when you need .count, indices, subscript
  • Only ask for RandomAccessCollection when you really need fast random access or slicing

8. Small Practice – Try these

  1. Write a generic function that prints the first and last element of anyCollection (use Collection constraint)
  2. Write a generic function that returns the number of elements and the first element (if exists) of any Sequence
  3. Write a function that takes any RandomAccessCollection and swaps the first and last element (only if there are at least 2 elements)

Paste your code here if you want feedback or want to see cleaner versions!

What would you like to explore next?

  • Sequence vs Collection vs RandomAccessCollection in depth
  • Writing your own custom collection type
  • Collection protocols in SwiftUI (ForEach, List, data sources)
  • Lazy collections (lazy, LazySequence, LazyMapCollection…)
  • Or move to another topic (optionals, switch, functions, mutability…)

Just tell me — we’ll continue in the same clear, patient, detailed style 😊

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *