Hunter Dolan Hunter Dolan - 1 month ago 9
Swift Question

Swift: Return an array of objects of subclassed type from a superclass

I have a Swift class that acts as a base class for other types of objects in my application. The class is for data modeling, so it implements various functions to save and retrieve objects from storage.

For the sake of the example, my class looks as follows:

class Base: NSObject {
class func objects() -> [Base] {
return []
}
}


And a subclass of the base looks as follows:

class Subclass: Base {

}


This works great because I can create an instance of the subclass and then get an array of objects:

let objects = Subclass.objects()


However, the array returned is set to the type
[Base]
.

Is there any way possible, to have
Subclass.objects()
return a
[Subclass]
automatically, without writing any additional code in the subclass?

My initial thought would be to write:

class func objects() -> [Self]


However, that causes a compiler error.

Answer

You can achieve this using a protocol and an extension:

protocol BaseProtocol {}

extension BaseProtocol {
    static func objects() -> [Self] {
        return []
    }
}

class Base: NSObject, BaseProtocol {}
class Subclass: Base {}

let objects = Subclass.objects()
Comments