编辑代码

class HTMLElement {
    var text: String?
    var name: String
    // 这里必须加lazy,因为在初始化的时候,先会初始化属性,
    // 但是此时self还没有构建好,所以这里必须设置lazy
    lazy var asHtml: () -> String = {
        [unowned self] in // 这里将self设置为无主引用,此时引用关系是从self->closure,
        if let text = self.text {
            return "<\(self.name)>\(text)</\(self.name)>"
        } else {
            return "<\(self.name) />"
        }
    }
    init(name: String, text: String?) {
        self.name = name
        self.text = text
    }
    deinit {
        print("\(name) deinit")
    }
}

var a: HTMLElement? = HTMLElement(name: "b", text: "Hello World")
print(a!.asHtml())
a = nil