Skip to content

Instantly share code, notes, and snippets.

@lalkrishna
Created January 17, 2023 07:33
Show Gist options
  • Save lalkrishna/3770ce3933feaf4d7c0d3f1323e7fd72 to your computer and use it in GitHub Desktop.
Save lalkrishna/3770ce3933feaf4d7c0d3f1323e7fd72 to your computer and use it in GitHub Desktop.
instantiate viewcontroller using identifier.
protocol Instantiatable {
static var storyboard: Storyboard { get }
static func instantiate() -> Self
}
extension Instantiatable where Self: UIViewController {
static func instantiate() -> Self {
// swiftlint:disable force_cast
UIStoryboard(storyboard).instantiateViewController(withIdentifier: String(describing: Self.self)) as! Self
}
}
enum Storyboard: String {
case main = "Main"
}
extension UIStoryboard {
convenience init(_ storyboard: Storyboard) {
self.init(name: storyboard.rawValue, bundle: nil)
}
}
extension UIViewController {
static func instantiate(storyboard: Storyboard) -> Self {
// swiftlint:disable force_cast
UIStoryboard(storyboard).instantiateViewController(withIdentifier: String(describing: Self.self)) as! Self
}
}
// Usage:
class ViewController: UIViewController, Instantiatable {
static let storyboard: Storyboard = .main
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment