Zoon Nooz Zoon Nooz - 6 months ago 150
Objective-C Question

How can I return instancetype in Swift

I want to make an extension of some class to return the runtime type object

for example, I create extenstion of class A

extension A {
class func niceObject() -> XXXXX { // in objective-c is instancetype
return ....
}
}


So anyone know there is instancetype keyword in Swift or not to replace
xxxxx
and I can call this function on subclass of A without manually cast

var b: B = B.niceObject()


Thanks

Answer

You can do it. Playground code below. It's self() that niceObject() has to return. Additionally, you must have a required init on the base class.

class A {
    required init() {
    }

    func whatClassAmI() -> String {
        return "Class A"
    }
}

class B: A {
    required init() {
        super.init()
    } 
    override func whatClassAmI() -> String {
        return "Class B"
    }
}

let a = A()
let sa = a.whatClassAmI() // "Class A", of course

let b = B()
let sb = b.whatClassAmI() // "Class B", of course

extension A {
    class func niceObject() -> Self {
        return self.init()
    }
}

let aa = A.niceObject()
let saa = aa.whatClassAmI() // "Class A"

let bb = B.niceObject()
let sbb = bb.whatClassAmI() // "Class B", as required
Comments