Swift Generics

A portrait painting style image of a pirate holding an iPhone.

by The Captain

on
May 20, 2023

The Basics of Swift Generics

Swift Generics are a powerful feature that allows you to write flexible and reusable code. They provide a way to write functions, types, and algorithms that can work with any type, not just a specific type. In this tutorial, we will explore the basics of Swift Generics with an example.

What are Generics?

Generics are a way of writing code that is both abstract and flexible. They allow you to write functions and types that can work with any data type or object. In Swift, Generics are represented using angle brackets (<>) and type placeholders.

You can think of Generics as a blueprint for creating functions and types that can work with any data type. By using Generics, you can avoid code repetition and make your code more maintainable and reusable.

Creating a Generic Function

Let's create a simple function that swaps two values, using Generics:

func swapTwoValues(_ a: inout T, _ b: inout T) {
    let temp = a
    a = b
    b = temp
}

In the function above, we used the placeholder type T. This type is used to represent any type that the function is called with. The function takes two parameters of type T, and the inout keyword indicates that the parameters are passed by reference.

We then create a temporary variable of type T, swap the values of the two inputs, and return the updated values. Because we used the inout keyword, any changes made to the input values inside the function persist outside the function.

Using the Generic Function

Now that we have created our Generic function, let's use it with different data types:

var a = 5
var b = 10
swapTwoValues(&a, &b)
print("a = \(a), b = \(b)") // Output: a = 10, b = 5

var strA = "Hello"
var strB = "World"
swapTwoValues(&strA, &strB)
print("strA = \(strA), strB = \(strB)") // Output: strA = World, strB = Hello}

As you can see from the code above, we were able to use the same swapTwoValues() function with two different data types (Int and String), thanks to the use of Generics.

Conclusion

Swift Generics are a powerful feature that allow you to write flexible and reusable code. By using placeholders to represent any data type, you can create functions and types that can work with any object. In this tutorial, we covered the basics of Generics using an example of a simple swapping function.