Sobes.tech
Middle

How can you add a function to an array in Swift?

sobes.tech AI

Answer from AI

Through extensions.

extension Array {
    // Example function that adds an element only if it is not already in the array
    mutating func appendUnique<Element: Equatable>(_ element: Element) where Element == Self.Element {
        if !self.contains(a: element) {
            self.append(element)
        }
    }

    // Generic contains function
    func contains<Element: Equatable>(a element: Element) -> Bool where Element == Self.Element {
        return self.contains(where: { $0 == element })
    }
}

var numbers = [1, 2, 3]
numbers.appendUnique(4) // [1, 2, 3, 4]
numbers.appendUnique(2) // [1, 2, 3, 4] - element 2 already exists

var strings = ["apple", "banana"]
strings.appendUnique("orange") // ["apple", "banana", "orange"]
strings.appendUnique("apple")  // ["apple", "banana", "orange"] - element "apple" already exists
How can you add a function to an array in Swift? — iOS - sobes.tech