Intro to Generics in Swift with examples
Why Generics?
Solve the problem of code duplication. Swift allows you to create
- Generic Types — for example custom struct, classes, enumerations that can work with any type
- 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
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
- A Type (that is conforming to a Protocol)
- Using where clause