Using custom initializers inside view controllers on iOS 13 or later.

StoryboardLoadable protocol

Using this protocol, we can now initialize our view controllers without the force unwrapping its properties while using storyboards.

Force unwrapping(!) is extracting the value of an optional and assuring compiler for it to have value. However this process has its downsides on runtime and crashes application if accessed value is nil.

Conforming protocol on view controller

Our view controller is inside Malignant.storyboard and its storyboard ID is same as its name which is MalignantViewController.

Define view controller

Now we could use our custom initializer to inject our view model into the view controller and use it to push onto navigation stack.



Apple introduced instantiateViewController(identifier:creator:) method on iOS 13 and before that people were using force unwrapping or optional types on properties while using storyboards. As I mentioned above, there are downsides of using force unwrapping. And defining non-optional type as optional fails the API contract.

Using this protocol you could define and create view controllers at ease. Also define clear boundaries on your API.

Thanks for reading.

iOS Developer, waiting AI takeover. @hsncr on GitHub and LinkedIn