Image source- @travelwithlace

Write reusable code with

Generics in Swift

Navdeep Singh
5 min readSep 10, 2019

--

Create efficient and reusable abstractions

Generics are a key feature in Swift, which combined with protocols gives performance, flexibility, and concise, comprehensible compile errors if we make a mistake while using them in code.

In this article we will discuss the generics system, use of protocols in generics constraints, @inlinable and more.

We have all worked with simple array examples like the following code a number of times:

var names = [“Eli”, “Adam”, “Simon”]

The code above is exact equivalent of using a variable with explicit type annotation as follows:

var names : [String] = [“Eli”, “Adam”, “Simon”]

and this in turn is a short form for the full generic type annotation:

var names : Array<String> = [“Eli”, “Adam”, “Simon”]

Most important and common thing among all these lines of code is that they are all doing exactly the same thing and the compiler is mapping under the hood to create safe and efficient code using both compile and run time type information. This is called Compiler type inference.

--

--

Navdeep Singh
Navdeep Singh

Written by Navdeep Singh

Author of Reactive programming with Swift, Engineering Manager — Exploring possibilities with new Tech.

No responses yet