Swift Language Initializers Convenience init

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Insert
> Step 2: And Like the video. BONUS: You can also share it!

Example

Swift classes supports having multiple ways of being initialized. Following Apple's specs this 3 rules must be respected:

  1. A designated initializer must call a designated initializer from its immediate superclass. For First Rule
  2. A convenience initializer must call another initializer from the same class.
  3. A convenience initializer must ultimately call a designated initializer. For Second and Third Rule
class Foo {

    var someString: String
    var someValue: Int
    var someBool: Bool

    // Designated Initializer
    init(someString: String, someValue: Int, someBool: Bool)
    {
        self.someString = someString
        self.someValue = someValue
        self.someBool = someBool
    }

    // A convenience initializer must call another initializer from the same class.
    convenience init()
    {
        self.init(otherString: "")
    }
    
    // A convenience initializer must ultimately call a designated initializer.
convenience init(otherString: String)
    {
        self.init(someString: otherString, someValue:  0, someBool: false)
    }
}


class Baz: Foo
{
    var someFloat: Float
    
    // Designed initializer
    init(someFloat: Float)
    {
        self.someFloat = someFloat
        
        // A designated initializer must call a designated initializer from its immediate superclass.
        super.init(someString: "", someValue: 0, someBool: false)
    }
    
    // A convenience initializer must call another initializer from the same class.
    convenience init()
    {
        self.init(someFloat: 0)
    }
}

Designated Initializer

let c = Foo(someString: "Some string", someValue: 10, someBool: true)

Convenience init()

let a = Foo()

Convenience init(otherString: String)

let b = Foo(otherString: "Some string")

Designated Initializer (will call the superclass Designated Initializer)

let d = Baz(someFloat: 3)

Convenience init()

let e = Baz()

Image source: The Swift Programming Language



Got any Swift Language Question?