Chapters

Hide chapters

Swift Cookbook

Live Edition · Multiplatform · Swift · Editor agnostic

Extend Types with Generics
Written by Team Kodeco

In Swift, it’s possible to extend existing types with genericss using the extension keyword. This allows you to add functionality to a type without modifying its original implementation.

Here’s an example of extending the Array type with a generic first(where:) function that returns the first element that satisfies a given predicate:

extension Array {
  func first<T>(where predicate: (Element) -> T?) -> T? {
    for element in self where predicate(element) != nil {
      return predicate(element)
    }
    return nil
  }
}

In this example, the first(where:) function takes a single argument, a closure that takes an element of the array and returns an optional of any type T. The function returns an optional of the same type T. The function iterates over the elements of the array and for the first element that satisfies the predicate, it returns the result of the predicate.

Here’s an example of how to use this function:

let numbers = [1, 2, 3, 4, 5, 6]
if let evenNumber = numbers.first(where: { $0 % 2 == 0 }) {
  print(evenNumber) // Output: "2"
}

In this example, you are using the first(where:) function to find the first even number in an array of integers. The closure passed as an argument to the function takes an element of the array and returns true if it’s even and false if it’s odd. The function iterates over the elements of the array and when it finds the first element that satisfies the predicate, it returns that element, which in this case is 2.

Since the first(where:) function uses generics, you can use this with other types of arrays as well:

let animals = ["zebra", "hamster", "dog", "cat", "anteater"]
if let firstAnimalWithShortName = animals.first(where: { $0.count <= 3}) {
  print(firstAnimalWithShortName)
}

You can also extend other types with generics, like classes, structs, enums and protocols, it’ll help you to add more functionality to them without modifying the original implementation.

Also, it’s important to note that this function isn’t part of the standard library but can be added to any project.

© 2024 Kodeco Inc.