Blog_UIStoryboardSafety icon indicating copy to clipboard operation
Blog_UIStoryboardSafety copied to clipboard

more simple

Open butcheryl opened this issue 8 years ago • 1 comments

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)

butcheryl avatar Oct 17 '16 15:10 butcheryl

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 {}

pepejeria avatar Mar 03 '18 10:03 pepejeria