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

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM