April 2026
Intermediate
683 pages
25h 29m
English
Generic functions is a powerful Swift feature that allows you to write flexible and reusable code. Instead of repeating similar but slightly different code blocks, you can generalize them with help of generics. In this section, we’ll go over examples demonstrating generics and highlighting their use cases.
To understand generic functions, let’s start with a case study in which two mostly similar but slightly different functions are present. Listing 5.74 demonstrates swapInts and swapStrings for that purpose.
// Functionsfunc swapInts(_ a: inout Int, _ b: inout Int) { let tmp = a a = b b = tmp}func swapStrings(_ a: inout String, _ b: inout String) { let tmp = a a = b b = tmp}// Main flow
Read now
Unlock full access