話不多說 直接上代碼
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