Returning the subclass in a UIViewController static

后端 未结 2 954
离开以前
离开以前 2021-01-16 03:59

Consider a base UIViewController class...

class Rooms: UIViewController {
    class func instantiate()->Rooms {
    }

    static func make()->Rooms {
         


        
2条回答
  •  夕颜
    夕颜 (楼主)
    2021-01-16 04:39

    I don't like to provide my own answer, but the solution is ..

    So the problem is, at editor time

    let d = Dining.make()
    

    "doesn't work", you have to do this

    let d = Dining.make() as! Dining
    

    (It DOES work at compile time, d becomes a Dining: it doesn't "work" at editor time.)

    So the solution is

    static func make()->Rooms {
        let emplacedAndSetup = self.instantiate()
        return emplacedAndSetup
    }
    

    becomes

    static func make()->T {
        let emplacedAndSetup = self.instantiate() as! T
        return emplacedAndSetup
    }
    

    So that's it.

    Note - it's entirely possible AppzForLife's solution works and/or is better as a general purpose "UIViewController auto-instantiator", but this is the answer to the question per se.

提交回复
热议问题