Designated vs Convenience vs Failable init (Init Types in swift)
Class, Struct and Enumeration need init method to create instance of that object. Class, Struct and Enumeration has their own init method. You can create an instance using default init method or by using custom init method.
Designated init:
Designated init is same as default initialiser. These are the primary initializers for a class or struct or enumeration.
Convenience init:
Convenience initializers are secondary, supporting initializers for a class. Convenience init is written in same style as designated init with extra keyword convenience
.
Bellow are the rules you need to follow when you’re using designated/Convenience init
- Designated init may or mayn’t call another designated init.
- If you’re using inheritance, Subclass designated/convenience init should call Superclass Designated init method.
- Convenience init can call another convenience init or designated init.
- But finally your convenience init/designated init should finally call super class designated init.
A inheritance means, A subclass can inherit its super class property, method and other characters.
As above e.g: super class has property a
and designated init is init(a: Int)
and convenience init convenience init()
. this convenience init is calls designated init.
Now if you inherit this super class in subclass. Instead of overriding the super init method, you can create your own convenience init method by using convenience init()
in subclass.
Failable init:
An initializer that might work or might not. You can create this init in struct, enumeration and in class using init?()
Failable init returns nil if something goes wrong. return value will be always optional. you need to unwrap it.
Advantages of Failable init:
- If you know that you can’t create the instance of object by using data provided by you, instead of creating an instance you can return nil.
- This returns an optional instance that will be nil if initialization failed.
I hope you find this blog helpful. If you enjoyed it, feel free to hit the clap button below 👏 to help others find it! and follow me on Medium. Thanks for reading. ❤❤❤❤