How to customise a view next to it’s declaration (in Swift)

acecilia
acecilia
Aug 9, 2017 · 2 min read

After declaring the views of an app you usually need some customisation. Most of the times, that customisation needs to be done only once. That code goes typically in the viewDidLoad function:

Personally, I prefer to do it next to it’s declaration:

This keeps the code more organised and the viewDidLoad function less cluttered: with multiple views, the viewDidLoad method can grow too much. The drawbacks are:

  • The initialization and return lines (14 and 17 of the image above) are kind of an overkill: they always need to be there, in addition of the lines of code related with the customisation.
  • You need to think of a name for the property inside the closure (line 14 in the above image). This is really not needed, whatever name will be valid because, in the end, the property has a name at it’s declaration (line 13).
  • You need to specify the type of the property (or specify the return type of the closure), because the compiler can not infer it from **such** a complex closure.

Today I had a 12h flight and spent some time thinking about this. In the end I got to the following implementation:

Which leads me with this neat way of customising a view next to it’s declaration:

Written by

acecilia

Whatever is in my mind: Swift, code and pizza

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade