Swift Generics and Generic Functions Example

1. Introduction

Generics are one of the most powerful features of Swift programming, allowing you to write flexible and reusable functions and types. With generics, you can write code that works with any type, subject to requirements that you define. This ensures type safety while retaining performance benefits.

2. Source Code Example

// A generic function to swap the values of two variables
func swapTwoValues<T>(_ a: inout T, _ b: inout T) {
    let temporaryA = a
    a = b
    b = temporaryA

var intA = 1
var intB = 2
swapTwoValues(&intA, &intB)
print("Swapped values: \(intA), \(intB)")

var stringA = "Hello"
var stringB = "World"
swapTwoValues(&stringA, &stringB)
print("Swapped values: \(stringA), \(stringB)")


Swapped values: 2, 1
Swapped values: World, Hello

3. Step By Step Explanation

1. We define a generic function swapTwoValues, with a placeholder type T which is a stand-in for the actual type, but does not specify what T is. The actual type to use in place of T will be determined each time the swapTwoValues function is called.

2. Inside the function, we use a temporary variable to hold the value of a, then assign the value of b to a, and finally assign the temporary value to b. This effectively swaps the values of a and b.

3. We demonstrate the generic function's flexibility by using it to swap two integers and then two strings. Since the function is generic, it can work with any type.