Tuesday, January 16, 2018

Swift Convenience Initializers

A class can have any number of designated Initializers.
In my case It’s a Downloader class which can be initialized using an URL or a String.



We can write 2 designated initialisers for this. Now with URL as parameter and other with String as parameter. Though we can do like this, Keeping an Initializer for each type of parameter, There is an issue here.



All the initialization code has to be duplicated in all designated initializers. Whatever we do in Designated initializer 1 should be kept in Designated Initializer 2 and so on.

To avoid this, we can use convenience initialisers as shown below.



Downloader class can also be instantiated using a url string value also using the convenience initializer. But, A convenience initializer should have to call any one of designated initializers of a class If that class in having only one convenience initializer.




One more use case of convenience initializer is that, We can simplify the initialization process by setting default values.




Here aspectRatio property can be set to a default value to simplify initialization.


Now you understood where and how to use convenience initializers.

  1. To simplify initialization process with default values.
  2. To avoid code redundancy in Designated Initializers.


There are some rules for Designated and Convenience Initializers.

  1. A designated initializer must call a designated initializer from its immediate superclass.
  2. A convenience initializer must call another initializer from the same class.
  3. A convenience initializer must ultimately call a designated initializer.

Take Aways:-


  • Convenience Initializers are just for developer’s convenient way of initializations keeping some parameters as default ones.
  • There is no thumb rule to use convenience initializers. 
  • Convenience Initializers can not be overridden.
  • There are 3 rules for Designated and Convenience Initializers
  • Only classes can have convenience Initializers. Structures can not.



Hope this post is useful. Feel free to comment incase of any queries.




No comments:

Post a Comment