Hunter Dolan Hunter Dolan - 1 year ago 89
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

Is there any way possible, to have
return a
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 Source

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()
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download