Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift - Refer to current class type in a static / class function

I've static functions to instantiate view controllers that look like

class AController: UIViewController {
  static func instantiate() -> AController {
    let storyboard = UIStoryboard(name: "AController", bundle: nil)
    let controller = s.instantiateInitialViewController() as? AController
    return controller!
  }
}

class BController: UIViewController {
  static func instantiate() -> BController {
    let storyboard = UIStoryboard(name: "BController", bundle: nil)
    let controller = storyboard.instantiateInitialViewController() as? BController
    return controller!
  }
}

I've a bunch of them so I'd like to make that cleaner as:

class MYViewController: UIViewController {
  class func instantiate() -> self.type {
    let storyboard = UIStoryboard(name: "\(self.type)", bundle: nil)
    let controller = storyboard.instantiateInitialViewController() as? self.type
    return controller!
  }
}

class AController: MYViewController {
}

class BController: MYViewController {
}

But I don't know of to dynamically refer to the type of the object in a static / class function, and how to have this refer to the subclass when called from a subclass. It's easy to do once an object has been instantiated with type(of: object)

like image 273
Guig Avatar asked Nov 09 '22 04:11

Guig


1 Answers

Try this:

class MYViewController: UIViewController {
    class func instantiate() -> Self {
        let storyboard = UIStoryboard(name: "\(self)", bundle: nil)
        let controller = storyboard.instantiateInitialViewController() as! Self
        return controller
    }
}

I'm not 100% sure it works because I didn't test your code directly (don't want to create a storyboard just for testing), but I wrote similar code to test it, which works:

class MYViewController: UIViewController {
    class func instantiate() -> Self {
        print("type: \(self)")
        return self.init()
    }
}
like image 51
Ole Begemann Avatar answered Nov 15 '22 07:11

Ole Begemann