Radek
Radek

Reputation: 329

Init with default vs convenience initialiser

Is there any difference between init with default value vs calling convenience initialiser ? I try to figure out when should I use convenience instead of init with default.

class Food
 {
    var name :String

    init(name : String = "Unknow")
    {
        self.name = name
    }
 }

And this :

 class Food
 {
    var name :String

    init(name : String)
    {
        self.name = name
    }

    convenience init()
    {
        self.init(name : "Unkow")
    }
 }

Upvotes: 0

Views: 562

Answers (1)

Yoichi Tagaya
Yoichi Tagaya

Reputation: 4577

Convenience initializer is easier for users of the class than a designated initializer with a default value because Xcode lists the two initializers by autocompletion.

Autocompletion for a designated initializer with a default value:

Screenshot with a default value

Autocompletion for a designated initializer and convenience initializer:

Screenshot with a convenience initializer

The screenshots are taken with Xcode 6.2. Unless Xcode supports autocompletion for default values, the convenience initializer is easier for the users, especially if you design a framework for people.

A disadvantage of a convenience initializer is, as Kelvin mentioned in his comment, you cannot use the convenience initializer from the subclass initializer.

Upvotes: 1

Related Questions