init相当于构造函数
deinit相当于析构函数
class InitAndDeinitExample { // Designated (i.e., main) initializer init () { print("I've been created!") } // Convenience initializer, required to call the // designated initializer (above) convenience init (text: String) { self.init() // this is mandatory print("I was called with the convenience initializer!") } // Deinitializer deinit { print("I'm going away!") } }
调用的例子:
var example : InitAndDeinitExample? // using the designated initializer example = InitAndDeinitExample() // prints "I've been created!" example = nil // prints "I'm going away" // using the convenience initializer example = InitAndDeinitExample(text: "Hello")
运行结果:
I've been created!
I was called with the convenience initializer