swift基础之类的初始化和反初始化

原创
2021/04/15 16:58
阅读数 29

类的初始化器

//类的初始化器
class Temperature {
    var number: Double
    let name: String
    
    init () {
        number = 20.0
        name = "abc"
    }
}

便捷初始化器convenience

class Temperature {
    var number: Double
    let name: String
    
    init () {
        number = 20.0
        name = "abc"
    }
	
    convenience init(fahrenheit: Double) {
        self.init()
        number = fahrenheit
    }
    
    convenience init(celsius: Double) {
        self.init(fahrenheit: celsius)
    }
}

var f = Temperature()
print(f.number)
//20.0

子类初始化器

class Person {
    var name: String
    var age: Int
    
    init(name: String, age: Int) {
        self.name = name
        self.age = age
    }

    convenience init() {
        self.init(name: "na", age: 0)
    }
	
    //反初始化器
    deinit {
        print("exit")
    }
}

class Teacher: Person {
    var salary: Int
    
    init(name: String, age: Int, salary: Int) {
        self.salary = salary
        super.init(name: name, age: age)
        self.name = name + "老师"
    }
    
    convenience init(name:String) {
        self.init(name: name, age: 25, salary: 5000)
    }
    
    func showInfo() {
        print("teacher name \(name), age \(age), salary \(salary)")
    }
}

var teacher: Teacher? = Teacher(name: "Atwal")
teacher!.showInfo()
//teacher name Atwal老师, age 25, salary 5000
teacher = nil
//exit
展开阅读全文
打赏
0
0 收藏
分享
加载中
更多评论
打赏
0 评论
0 收藏
0
分享
返回顶部
顶部