Swift 2 语言精要 - Initialization and Deinitialization

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

 

posted @ 2016-03-28 11:08  Master HaKu  阅读(216)  评论(0编辑  收藏  举报