Intro to Generics in Swift with examples

Why Generics?

Solve the problem of code duplication. Generics can be used to create a Generic data structure like Stack or Queues. Generics can also be used to create Generic functions.

Q: Examples of Generic in Swift Standard Library

Arrays, Dictionary

Generic Data Structure

Examples of two generic data structures (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

The angled brackets <> tell the compiler

Constraining Generic Functions

Here T: Number where T is the placeholder and :Number indicates that the Generic Type T should

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