Swift classes supports having multiple ways of being initialized. Following Apple's specs this 3 rules must be respected:
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)
let a = Foo()
let b = Foo(otherString: "Some string")
let d = Baz(someFloat: 3)
let e = Baz()
Image source: The Swift Programming Language