方便初始化

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 ë