Swift Type Initialization with Closures

Let start with the Problem:
First, let’s take a look at the traditional code writing style
There is some problem with this way of writing.
- Configure each view
- Installing each view
- Bloated viewDidLoad: Code becomes poorly visible as the number of views increases.
- Not able to provide some customization or setup to property at time of object Initialization.
Solutions: Initialization Closure
What is Initialization Closure?
When Type initialized, Closure belong to type is called and its return value is assigned as the default value for the store property.
If your property’s default value requires some customization or setup, you can use a closure or a global function to provide a customized default value for that property
here in the above example Type Address
have closure
that return value and assign to store property i.e country
.
Note: It’s the same as the global function return value and assigns to store property.
let's come to our main problem after having Closure Initialization now it looks like
Here, the setting(customization) of each view is done in each closure, and each property has a set view by default.
viewDidLoad
allow us to concentrate on the role of installing(add) each view.
I think it's much easier to understand where and what is being done.
Important point
- At the end of the closure
()
given ()
By adding, the closure is executed immediately and the value returned from the closure is assigned to the stored property.- You can not use
self
or other property, a method that belongs to Type In the closure. This is because each closure has not been initialized when it is executed.

Advantages:
- Provide the customization or setup to store property as default value.
- Initialization Closure prevents
viewDidLoad
from bloating. - Improve the code readability.