Swift Type Initialization with Closures

Shantaram Kokate
2 min readMar 6, 2021

--

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.

  1. Configure each view
  2. Installing each view
  3. Bloated viewDidLoad: Code becomes poorly visible as the number of views increases.
  4. 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.

viewDidLoadallow 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 selfor 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:

  1. Provide the customization or setup to store property as default value.
  2. Initialization Closure prevents viewDidLoad from bloating.
  3. Improve the code readability.

If you like this post, please share and give claps so others can find it 👏👏

You can follow me on Medium for updated articles. Also, connect with me on LinkedIn, Twitter.

If you have any comments, questions, or recommendations, feel free to post them in the comment section below!👇

Sign up to discover human stories that deepen your understanding of the world.

--

--

Shantaram Kokate
Shantaram Kokate

No responses yet

Write a response