Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the use case for convenience initializer?

In swift there is the concept of designated initializer (which is the "normal" constructor we know from other languages, I assume).
But there is also something called Convenience Initializer, which I do understand how to write, but the point is lost on me.
As, If I understand correctly, you can achieve the same thing without writing the keyword convenience, or not?

like image 721
Itay Moav -Malimovka Avatar asked Nov 10 '22 06:11

Itay Moav -Malimovka


1 Answers

As I understand, the only point in those initializers is convenience. Sometimes it happens that, we often need to create some object with same arguments over and over again. In that case, we can just add another init method which takes much less parameters and the remaining ones are hard coded.

For example, some Logger class

init(type: LoggerType, filepath: String, configurations: LoggerConfig, etc.)

It might be that we often use this logger with same arguments. To avoid duplicating code, we can add a convenience initializer with some default values

convenience init(){ self.init(type: LoggerType.SomeType, filepath: "/log", configurations: LoggerConfig.Default) }

like image 200
Samurai Girl Avatar answered Nov 14 '22 23:11

Samurai Girl