Created
May 10, 2018 18:17
-
-
Save bourgeois/11096d8bfb5e2b71055936d549f8fd51 to your computer and use it in GitHub Desktop.
Better UIStoryboard and UIViewController instantiation
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// UIStoryboardExtension.swift | |
// | |
import Foundation | |
/* | |
This is an extension to help with UIStoryboard and UIViewController instantiation from identifier. | |
The ultimate goal is to remove hard coded UIStoryboard and UIViewController identifiers in code. | |
Usage: Your UIViewController must conform to StoryboardIdentifiable. | |
When impact will be easier to mesure, we can conform all UIViewController to this protocol by an extension | |
extension UIViewController: StoryboardIdentifiable { } | |
But for now, we can provide this extension as a opt-in model instead. | |
Storyboard identifier needs to match UIViewController class name. | |
Implmentation example | |
let storyboard = UIStoryboard.storyboard(.accountSettings) | |
This will instantiate AccountSettings.storyboard from disk | |
let profileViewController: ProfileViewController = storyboard.instantiateViewController() | |
profileViewController is a ProfileViewController instance because storyboard identifier | |
is ProfileViewController inside AccountSettings.storyboard. | |
*/ | |
extension UIStoryboard { | |
enum Storyboard: String { | |
case accountSettings | |
var filename: String { | |
return rawValue.capitalized | |
} | |
} | |
convenience init(storyboard: Storyboard, bundle: Bundle? = nil) { | |
self.init(name: storyboard.filename, bundle: bundle) | |
} | |
func instantiateViewController<T: UIViewController>() -> T where T: StoryboardIdentifiable { | |
if let viewController = self.instantiateViewController(withIdentifier: T.storyboardIdentifier) as? T { | |
return viewController | |
} else { | |
fatalError("Couldn't instantiate view controller with identifier \(T.storyboardIdentifier) ") | |
} | |
} | |
} | |
protocol StoryboardIdentifiable { | |
static var storyboardIdentifier: String { get } | |
} | |
extension StoryboardIdentifiable where Self: UIViewController { | |
static var storyboardIdentifier: String { | |
return String(describing: self) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment