andyyhope / Blog_UIStoryboardSafety

Example code for a blog post i wrote on Medium
MIT License
99 stars 7 forks source link

more simple #4

Open butcheryl opened 8 years ago

butcheryl commented 8 years ago

I have an idea:

// swift 3.0

public protocol StoryboardInstantiable { }

extension StoryboardInstantiable where Self: UIViewController {
    public static func create(of storyboard: Storyboard) -> Self {
        return UIStoryboard(storyboard: storyboard).instantiateViewController()
    }
}

extension UIViewController: StoryboardInstantiable { }
let vc = HomeViewController.create(of: .Home)
pepejeria commented 6 years ago

Swift 4 (no compiler warnings) - all ideas combined:

extension UIStoryboard {

    enum Storyboard: String {
        case main
        case customer

        var filename: String {
            return rawValue.capitalized
        }
    }

    convenience init(storyboard: Storyboard, bundle: Bundle? = nil) {
        self.init(name: storyboard.filename, bundle: bundle)
    }

    func instantiateViewController<T>() -> T where T: StoryboardInstantiable {
        guard let viewController = instantiateViewController(withIdentifier: T.storyboardIdentifier) as? T else {
            fatalError("Couldn't instantiate view controller with identifier \(T.storyboardIdentifier)")
        }

        return viewController
    }

}

protocol StoryboardInstantiable {

    static var storyboardIdentifier: String { get }

}

extension StoryboardInstantiable where Self: UIViewController {

    static var storyboardIdentifier: String {
        return String(describing: self)
    }

    static func create(of storyboard: UIStoryboard.Storyboard) -> Self {
        return UIStoryboard(storyboard: storyboard).instantiateViewController()
    }

}

extension UIViewController: StoryboardInstantiable {}