The Problem: I have a view controller, that holds two variables, without which the controller isn't able to work. So, by concept, those variables are mandatory or non-optional.
However, I declared them optional, which results in guard statement in the first lines of nearly every single method. The reason for making them optional is:
- I'm not able to give them reasonable default values, they need to be set from outside during initialization
- I initialize the controller with
storyboard?.instantiateViewControllerWithIdentifierso there is no way (as far as I know) to define my own initializer which takes the necessary values. This would, obviously my favorite solution. - I don't want to make them non-optional just by declaration (!), to avoid runtime problems, that could be solved by them compiler
Variable declaration:
var dataSource : MyDataSource?
var cellAndHeaderManager: MyCellAndHeaderManager?
Typical method start:
guard let cellAndHeaderManager = cellAndHeaderManager else {return UICollectionReusableView()}
let header = cellAndHeaderManager.headerForSection(collectionView, indexPath: indexPath)
guard let dataSource = dataSource else {return header}
Initialization:
if let newController = storyboard?.instantiateViewControllerWithIdentifier("MyViewController") as? MyCollectionViewController {
newController.dataSource = dataSource
newController = cellAndHeaderManager
}
What I'd like to do:
newController = MyCollectionViewController(dataSource, cellAndHeaderManager)
Any ideas?
class funcas in my answer.