When you create an object in Swift, a special method initializer is called.
The initializer is the method that you use to set up the initial state of an object and is always named init.
Swift has two types of initializers, convenience initializers and designated initializers.
A designated initializer sets up everything you need to use that object, often using default settings where necessary.
A convenience initializer sets up the instance by allowing for more information to be included in the initialization.
A convenience initializer must call the designated initializer as part of its setup.
In addition to initializers, you can run code when deleting an object, in a method called a deinitializer.
deinitializer method is named deinit, and it runs when the retain count of an object drops to zero and is called right before the object is removed from memory.
You can do any necessary cleanup in the deinitializer:
class Car { // Designated (i.e., main) initializer init () { /*from w w w . ja va2 s . com*/ print("Designated") } // Convenience initializer, required to call the designated initializer (above) convenience init (text: String) { self.init() // this is mandatory print("convenience initializer!") } // Deinitializer deinit { print("Deinitializer") } } var example : Car? // using the designated initializer example = Car() example = nil // using the convenience initializer example = Car(text: "Hello")
An initializer can also return nil.
This is useful when your initializer cannot construct an object.
We used this feature earlier when we were converting one type into another:
let three = Int("3") // 3
An initializer that can return nil is known as a failable initializer.
You should put a question mark after the init keyword, and return nil if the initializer decides that it can't successfully construct the object:
// This is a convenience initializer that can sometimes fail, returning nil. convenience init? (value: Int) { self.init() if value > 5 { return nil } } var failableExample = Car(value: 6) // nil print(failableExample)
When you use a failable initializer, it will always return an optional, even if the initialization succeeds: