Returning the subclass in a UIViewController static

后端 未结 2 955
离开以前
离开以前 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: Rooms>()->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.

    0 讨论(0)
  • 2021-01-16 04:57

    You can do something like this.

    class RoomBase: RoomProtocol {
        // things common to every room go here
        required init() {}
    }
    

    You can put in RoomBase all the stuff you want the other rooms to inherit.

    Next you put the make() method into a protocol extension.

    protocol RoomProtocol: class {
        init()
    }
    
    extension RoomProtocol where Self: RoomBase {
        static func make() -> Self {
            let room = Self()
            // set up
            return room
        }
    }
    

    Now you can write

    class Dining: RoomBase {}
    class Bath: RoomBase { }
    

    And this code will work

    let dining: Dining = Dining.make()
    let bath: Bath = Bath.make()
    
    0 讨论(0)
提交回复
热议问题