Applying superclass array extensions to arrays of subclass instances

131 views Asked by At

Is there a way to use an array extension that has been applied to a superclass on arrays of subclass instances? I am attempting to do so in the following way:

Extension on superclass:

extension Array where Element == Superclass {

    func appending(_ object:Element)-> [Element] {
        var array = self
        if self.filter({$0.id == object.id}).count == 0 {
            array.append(object)
        }
        
        return array
    }
}

Implementation on subclass array:

var subArray = [Subclass]()
subArray = subArray.appending(someObject)

However, this gives me the following compiler error:

"Referencing instance method 'appending' on 'Array' requires the types 'Subclass' and 'Superclass' be equivalent."

Is there some way to achieve this functionality, or do I have to create separate extensions for each subclass?

1

There are 1 answers

0
Sweeper On BEST ANSWER

Use : rather than == to mean "a subtype of":

class Superclass {
    
}

class Subclass : Superclass {
    
}

// here!
extension Array where Element: Superclass {
    func f() {}
}

let a = [Subclass]()
a.f() // compiles!