Sitemap
Better Programming

Advice for programmers.

Generics in Swift

How can you use this “magical” feature of Swift? What are the advantages?

7 min readNov 5, 2019

--

Press enter or click to view image in full size
Photo by timJ on Unsplash

Generics are used to cut down on code reuse and enables abstraction of problems. Some say that this is an advanced feature of Swift, but I disagree. Once you get used to it, it becomes quite easy (as we shall see).

Difficulty: Easy | Normal | Challenging

Prerequisites

Some basic understanding of functions and methods in Swift.

Terminology

Generics: Reusable functions and types that can work with any type (or subset of a certain type.

Method signature: A combination of the method name and the parameter list that is used for a function.

Why It Matters — And How Arrays Might Use Generics

Generics are a powerful feature, and one that is often asked about during interviews to try to find the breadth of your knowledge.

You already use generics: Arrays allow you to take any type and hold them without having to specify a different type of array for each. Swift’s type inference means that this all feels rather seamless and easy.

--

--

No responses yet