Dudi Dudi - 4 months ago 18
Swift Question

Method that returns object of type which was called from

So I have two classes

Base
and
More
which looks like this

class Base:NSObject {
class func whatsMineType() -> Base {
return Base()
}
}

class More:Base {

}


And if I call method
Base.whatsMineType()
and
More.whatsMineType()
both of them gave me object of type
Base
. Is there a way to modify method
whatsMineType()
, without overriding it in
Base
, so it would return object of type which was called from?

My goal is that
Base.whatsMineType()
would return
Base
type object and
More.whatsMineType()
would return
More
type object.

I've tried with generic types but I don't have much experiance with them. Any suggestions will be super appreciated.

Edit
As I tried to explain this isn't the point of finding correct type but rather how to instantiate object with correct one.

Answer

As you're at static scope, you can simply call self.init() to do this. You'll also have to define a required initialiser to ensure that all subclasses can be constructed with it.

class Base : NSObject {

    // mark init() as required to ensure that all subclasses can be constructed with it
    required override init() {}

    class func whatsMineType() -> Self {
        return self.init()
    }
}

class More : Base {}

let b = Base.whatsMineType()
print(b.dynamicType) // Base

let m = More.whatsMineType()
print(m.dynamicType) // More