方便初始化

Swift 類支援多種初始化方式。遵循 Apple 的規範,必須遵守這 3 條規則:

  1. 指定的初始值設定項必須從其直接超類呼叫指定的初始值設定項。 StackOverflow 文件
  2. 便捷初始化程式必須從同一個類呼叫另一個初始值設定項。
  3. 便捷初始化器必須最終呼叫指定的初始化器。 StackOverflow 文件
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)
    }
}

指定初始化程式

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

方便 init()

let a = Foo()

便利 init(otherString:String)

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

指定的初始化程式(將呼叫超類指定的初始化程式)

let d = Baz(someFloat: 3)

方便 init()

let e = Baz()

影象源: 該夫特程式設計 LANGUAG ë