Liam SY Kim
by Liam SY Kim
1 min read

Categories

To develope my own app, I have browsed others github swift code. From a extension for making UIColor possible to use hex, I found convenience init.

This is the reason I studied it.

extension UIColor {
    convenience init(hex: Int) {
        self.init(red: CGFloat((hex & 0xFF0000) >> 16) / 255.0, green: CGFloat((hex & 0x00FF00) >> 8) / 255.0, blue: CGFloat(hex & 0x0000FF) / 255.0, alpha: 1)
    }
}

They did not add those things on init() but on convenience init().

Therefore, the question is..

What is the defference between (designated) init and convenience init?

Designated init is default initatializer in swift.

Designated init helps initializing all of properties in that class or structure.

It has a condition to work which should initiate whole properties.

Below example shows us well about it.

class Fruit {
    var name: String
    var color: String
    var price: Int
    init(name: String, color: String, price: Int) {
        self.name = name
        self.color = color
        self.price = price
    }
}

What if remove self.price = price?

Yes, compilier warns developer to initiate whole properties.

But then, how could you initialize only specific properties?

Yes, use convenience init

convenience init set some parameters of designated init which is given from developer as default value, and then initialize it.

From above sentence, you can predict designated init should declared first before declaringconvenience init.

Additionaly, convenience init should call other initializer on same class.

Above things are two important rules to use convenience init

By adding convenience init on Fruit class, developer can just type name and color.

Price will be fixed as 10.

class Fruit {
    var name: String
    var color: String
    var price: Int
    init(name: String, color: String, price: Int) {
        self.name = name
        self.color = color
        self.price = price
    }
    
    convenience init(name: String, color: String) {
        self.init(name: name, color: color, price: 10)
    }
}

Conclusion

Convenience init is good to use as extension for additional initializer based on default.

UIColor example which I show you first is usueful way to use it!

Reference