Nick Keets
Nick Keets

Reputation: 3398

class function with generic return value

Right now I have the following classes:

class A {
    class func instantiate() -> A {
        return MakeObject()
    }
}

class B: A {}

let x = B.instantiate()

This results in x being of type A. How can I change instantiate in order to return an instance of the subclass that was called from? In other words, so that x ends up being of type B.

EDIT:

This is what I used to solve it, based on Martin R's answers:

class A {
    class func instantiate() -> Self {
        func helper<T>() -> T {
            return MakeObject() as! T
        }

        return helper()
    }
}

Upvotes: 1

Views: 142

Answers (1)

Martin R
Martin R

Reputation: 539815

The returns type needs to be Self (which is the concrete type when the class method is called), and initialization must be done with a required init method (which can be overridden in a subclass):

class A {

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

    required init() {

    }
}

class B: A {}

let x = B.instantiate() // `x` has type `B`

Alternatively, just define an init method

init(parameters ...) {

}

which "automatically" returns instances of the class that is is called on.

Upvotes: 4

Related Questions