Cristik
Cristik

Reputation: 32786

Overload Array function based on the type of its elements

Is it possible to achieve something like this in Swift?

extension Array {
    func processItems<Element: Protocol1>() { 
        for item in self {
            // deal with Protocol1 objects
        }
    }

    func processItems<Element: Protocol2>() {
        for item in self {
            // deal with Protocol2 objects
        }
    }
}

What I want to achieve is to extend the Array and overload processItems based on the type of elements in the array.

An alternative would be to either have a single function and to use optional casting/binding, however I'd loose type safety this way, and might end up with a mammoth function containing a lot if if-let's

func processItem() {
    for item in self {
        if let item = item as? Protocol1 {
            // deal with Protocol1 objects
        } else if let item = item as? Protocol2 {
            // deal with Protocol2 objects
        }
    }
},

or to declare processItems as a free function:

func processItems<T: Protocol1>(items: [T]) {
    // ...
}

func processItems<T: Protocol2>(items: [T]) {
    // ...
}

However I'd like to know if I can "embed" the function into the Array class, to keep it localized. If this is possible, then the technique could be applied to other generic classes (either built-in or custom).

Upvotes: 0

Views: 98

Answers (1)

jtbandes
jtbandes

Reputation: 118671

How about this?

extension Array where Element: Protocol1 {
    func processItems() {
        for item in self {  // item conforms to Protocol1
            ...

Upvotes: 3

Related Questions