The Magical Power of Convenience Initializers in Swift

Fidan Musazade
2 min readNov 29, 2020

Classes group a set of behaviors and properties of an object by abstracting some parts of code that need to remain unknown to its user while keeping some other parts open for change. Often as software engineers, we work with classes that have been composed by other developers.

While mostly the way these classes are designed to fit our purposes, sometimes they lead to code duplication, unnecessary inheritance, and other similar problems. Some of these problems can easily be fixed if the programming language we write our code enabled us to create constructors (initializers from now on) according to our needs.

For example, every time we initialize a UICollectionView, we call UICollectionView(frame:collectionViewLayout:) specifying its frame and layout. However, does this initializer satisfy our needs? Of course, not. We have not specified the background color for the collection view (which is black for some reason by default), we have not specified its delegate, dataSource, or registered a cell class with an identifier for it. Thus every time we initialize a UICollectionView we also need to specify all those values as below:

Now we can assume we have fully initialized a collectionView, and it is ready for use. What if we need to use a collection view not in one place but multiple other occurrences? The first idea that comes to mind is to copy/paste the above code. Although this fixes our problem, it causes yet another problem — DUPLICATE CODE. Well, what we can do to avoid it?

We can, of course, subclass UICollectionView and do this:

However in this case:

  • We hardcode the number of cells.
  • We hardcode the background-color
  • We hardcode cell class
  • We hardcode delegate

Fortunately Swift enables us to use a feature called convenience initializers. What is it? Let us see in action:

The above code now will enable us to initialize the UICollectionView according to our needs, fully-customizable without code duplication, inheritance:

That is it. The UICollectionView instance is ready for use.

--

--

Fidan Musazade

Data Scientist & Machine Learning Engineer @ The International Bank of Azerbaijan