本文共 786 字,大约阅读时间需要 2 分钟。
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 initializerexample = InitAndDeinitExample() // prints "I've been created!"example = nil // prints "I'm going away"// using the convenience initializerexample = InitAndDeinitExample(text: "Hello")
运行结果:
I've been created!
I was called with the convenience initializer
转载地址:http://djkzl.baihongyu.com/