0

I have the bellow callback in a class:

class something: NSObject { 
  //some other code but NO Init()

   var done:((Bool)->())?
 }

I try using it as seen bellow (called on didSet of another var):

done!(true)//error

This however leads to the app crashing at this spot.

What am I doing wrong and how can I fix it? I believe that the issue may be related to not having initializers??

I should add that I use it like this in another class:

currentPost.done = { [weak self] (done) in
            if done {
                self.update(line: currentPost.line!)
            }
        }
  • Have you assigned a closure to `done` at any point? If not, it will be `nil` and force unwrapping will crash. You can use `done?(true]` to conditionally unwrap – Paulw11 Jul 26 '19 at 20:53
  • What if `currentPost.line` is `nil`. You should not use ! unless you know it is safe, but I would start will a conditional rather than forced unwrap of `done` a super my previous comment and see if that helps. – Paulw11 Jul 26 '19 at 20:56
  • @Paulw11 I dont think I ever give it a closer, how would I do that? –  Jul 26 '19 at 21:06
  • You do. Your edit shows that. `done` accepts a closure. That is its type. A closure in Swift is an anonymous function that is assigned to a variable, argument or property – Paulw11 Jul 26 '19 at 21:08
  • @Paulw11 I made it conditional and although it does not crash now the call back does not run that block... –  Jul 26 '19 at 21:09
  • So either the callback is being triggered before `done` has a value or the object that assigned the closure to `done` is being released before the callback is triggered (you have `weak self` so `done` won't cause the assigning object to be held in memory if there are no other strong references). You need to show more code so we can see the relationship between the callback and `currentPost` – Paulw11 Jul 26 '19 at 21:12

1 Answers1

0

Thanks to @Paulw11 in the comments I figured out how to make it work. The solution was to do the following:

    class something: NSObject { 
  //some other code but NO Init()

   var done:((Bool)->())?
   var do : Type { didSet { action() }}//Do this on a background thread so that the callback gets a value before its done...
   func action() {}
 }