Intro to Generics in Swift with examples

Neeraj Sharma
2 min readApr 27, 2020

Why Generics?

Solve the problem of code duplication. Swift allows you to create

  1. Generic Types — for example custom struct, classes, enumerations that can work with any type
  2. Generic functions

Q: Examples of Generics in Swift Standard Library

Arrays, Dictionary

Generic Type

Examples of two generic types (Queue and Stack). Here Element is the placeholder type and Queue<Element> and Stack<Element> — the angled brackets tell the compiler that Element is only a place holder inside the function body and function definition. The actual type of Element is determined only at runtime.

Usage of Generic Stack and Generic Queue

Usage of create, enqueue and dequeue Queue<Int>
Output dequeue a value from the Queue<Int>

Generic Functions

T is the placeholder type and referred to as the type parameter.

Constraining Generic Functions using protocols

Here T: Number where T is the placeholder and :Number indicates that the Generic Type T should conform to Numeric protocol

Generics can be constrained to

  1. A Type (that is conforming to a Protocol)
  2. Using where clause

--

--

Neeraj Sharma

Mobile application developer, an urban traveller, and a passionate photographer — “programming is a creative process almost like story telling”