Alex Staravoitau
Alex Staravoitau

Reputation: 2268

Extension func for a Swift Array taking any object as an argument

I'm trying to implement a simple extension function for Array in Swift that will "toggle" the element — if the value is in the Array already, it should be removed, if there's no such value, it should be added to the array.

So I reckon it should look something like:

extension Array {

    mutating func toggle(value: Element) {
        if let index = indexOf(value) {
            removeAtIndex(index)
        } else {
            append(value)
        }
    }

}

This code won't build saying: "Can not invoke 'indexOf' with an argument list of type '(Element)'". I guess, we should somehow tell the compiler that "value" argument should conform to the Equatable protocol, but how can I specify that?

Upvotes: 3

Views: 331

Answers (1)

Eric Aya
Eric Aya

Reputation: 70098

You just have to make the Array's generic "Element" conform to "Equatable" like this:

extension Array where Element: Equatable {

    mutating func toggle(value: Element) {
        if let index = indexOf(value) {
            removeAtIndex(index)
        } else {
            append(value)
        }
    }

}

Upvotes: 2

Related Questions