Swift 学习笔记 ,解决Swift闭包中循环引用的三种方法

话不多说 直接上代码

class SmartAirConditioner {
    var temperature:Int = 26
    //类引用了函数
    var temperatureChange:((Int)->())!
    
    init() {
        /*
         [weak self] 表示 self为可选型 可以为nil 所以在使用的时候必须解包
         [unowned self]由于在使用前要保证一定有这个对象 所以不必解包
         
         */
//        //这是类似于oc的解决方法。
//        weak var tempSelf = self
//        temperatureChange = {newTemperture in
//            if abs(newTemperture - (tempSelf?.temperature)!) >= 10 {
//                print("温度变化不大 可以调动")
//            }
//        }
//        temperatureChange = {[weak self] newTempearture in
//        //函数中又引用了self 造成了循环引用
//            if abs(newTempearture - self!.temperature) >= 10 {
//                print("温度变化太大")
//            }
//            else {
//                self!.temperature = newTempearture
//                print("这个不错")
//            }
//        }
                temperatureChange = {[unowned self] newTempearture in
                //函数中又引用了self 造成了循环引用
                    if abs(newTempearture - self.temperature) >= 10 {
                        print("温度变化太大")
                    }
                    else {
                        self.temperature = newTempearture
                        print("这个不错")
                    }
                }
        
    }
    deinit {
        print("Smart 被销毁了")
    }
    
}

var airCon:SmartAirConditioner? = SmartAirConditioner()
airCon?.temperature
airCon?.temperatureChange(100)
airCon?.temperatureChange(24)
airCon = nil