how to call deinit method within class definition in swift -


i want define method can destroy instance belongs when variable in class has increased value. attempted following:

 var calledtimes = 0 //some other method update value   func shoulddestroyself(){    if calledtimes == max_times {      denit    }  }  

but error message saying "expect '{' deinitializers".

is there anyway self-destruct within class?

you can create protocol self destruction based on criteria. here's example using class

class selfdestructorclass {     var calledtimes = 0     let max_times=5     static var instancesofself = [selfdestructorclass]()      init()     {         selfdestructorclass.instancesofself.append(self)     }      class func destroyself(object:selfdestructorclass)     {         instancesofself = instancesofself.filter {             $0 !== object         }     }      deinit {         print("destroying instance of selfdestructorclass")     }      func call() {         calledtimes += 1         print("called \(calledtimes)")         if calledtimes > max_times {             selfdestructorclass.destroyself(self)         }     } } 

you can derive class class , call call() on object. basic idea have ownership of object @ 1 , 1 place , detach ownership when criteria met. ownership in case static array , detaching removing array. 1 important thing note have use weak reference object wherever using it.

e.g.

class viewcontroller: uiviewcontroller {      weak var selfdestructingobject = selfdestructorclass()      override func viewdidload() {         super.viewdidload()         // additional setup after loading view, typically nib.     }      override func didreceivememorywarning() {         super.didreceivememorywarning()         // dispose of resources can recreated.     }      @ibaction func countdown(sender:anyobject?)     {         if selfdestructingobject != nil {             selfdestructingobject!.call()         } else {             print("object no longer exists")         }     } } 

Comments