Swift Language Using Generics to Simplify Array Functions


Example

A function that extends the functionality of the array by creating an object oriented remove function.

// Need to restrict the extension to elements that can be compared.
// The `Element` is the generics name defined by Array for its item types.
// This restriction also gives us access to `index(of:_)` which is also
// defined in an Array extension with `where Element: Equatable`.
public extension Array where Element: Equatable {
    /// Removes the given object from the array.
    mutating func remove(_ element: Element) {
        if let index = self.index(of: element ) {
            self.remove(at: index)
        } else {
            fatalError("Removal error, no such element:\"\(element)\" in array.\n")
        }
    }
}

Usage

var myArray = [1,2,3]
print(myArray)

// Prints [1,2,3]

Use the function to remove an element without need for an index. Just pass the object to remove.

myArray.remove(2)
print(myArray)

// Prints [1,3]