Storyboards should allow dependency injection via initializer by providing NSCoder instance
| Originator: | arkadiusz.holko | ||
| Number: | rdar://29734167 | Date Originated: | 19-Dec-2016 04:21 PM |
| Status: | Duplicate of 27213719 (Open) | Resolved: | |
| Product: | iOS + SDK | Product Version: | 10.1 |
| Classification: | Enhancement | Reproducible: | N/A |
Summary:
To be able to initialize a view controller with a view defined in a storyboard from code you have to use:
- UIStoryboard.instantiateViewController(withIdentifier:) or
- UIStoryboard.instantiateInitialViewController()
Those methods in turn call init(coder:) on the view controller. This doesn't play well with Swift's optionality. If the view controller requires some data to be set on it to work it has to use properties that are either optional or have an implicitly unwrapped optional attribute:
- var dependency: SomeType? or
- var dependency: SomeType!
So, the fact that some dependency wasn't set can be found only at runtime. If UIStoryboard had a method like `decoder(forViewControllerIdentifier identifier: String) -> NSCoder` it would be possible to define an initializer on a view controller that takes both that NSCoder instance and all other objects that it requires to work, e.g.:
class DetailsViewController: UIViewController {
let dependency: SomeType
init?(coder aDecoder: NSCoder, dependency: SomeType) {
self.dependency = dependency
super.init(coder: aDecoder)
}
}
We could then initialize it by calling that init directly:
let detailsViewController = DetailsViewController(coder: decoder, dependency: dependency)
This would solve a common issue of not being able to use dependency injection via initializer. At least when we don't use segues.
Expected Results:
We should be able to use dependency injection via initalizer when using storyboards (which provide really nice features!).
Actual Results:
We aren't able to use dependency injection via initializer with storyboards.
Notes:
Based on a blog post: http://holko.pl/2016/12/14/storyboards-dependency-injection/
Comments
Please note: Reports posted here will not necessarily be seen by Apple. All problems should be submitted at bugreport.apple.com before they are posted here. Please only post information for Radars that you have filed yourself, and please do not include Apple confidential information in your posts. Thank you!