SWIFT / CHAPTER 12

Generic algorithms and constraints

Advanced

Preserve type relationships while requiring only needed capabilities.

By the end of this chapter

  • Use a type parameter for related values
  • Constrain equality-based algorithms
  • Keep copy guarantees precise

The idea

A generic function uses type parameters to express relationships among its inputs and outputs. A first-element helper can return T? for an input [T], preserving the caller’s element type. A constraint such as T: Equatable permits equality comparisons inside the implementation. Avoid returning Any when the operation can retain a useful static relationship without losing flexibility.

Constraints should follow the operations the algorithm actually performs. Equality-based search does not require ordering, while sorting needs a comparison policy. Generic array copying retains Swift’s value semantics for the array container, but class instances stored as elements are still references to shared objects. Document independence at the right level so a caller does not assume an outer copy recursively duplicates an arbitrary object graph.

Swift example
func firstIndex<T:Equatable>(_ values:[T],of target:T)->Int? {for i in values.indices {if values[i]==target{return i}};return nil}
print(firstIndex(["a","b","a"],of:"a") ?? -1)
print(firstIndex([Int](),of:4) ?? -1)
Result
0
-1

The generic search preserves first-match behavior and represents empty or absent cases with nil.

Try it yourself

Write an Equatable-based function that counts occurrences without modifying its array.

Use your own editor for this exercise. Runnable challenges on CodeQuest are available for JavaScript, Python, and SQL.

CHECK YOUR UNDERSTANDING

Chapter checkpoint

What permits == between values of a generic type T?