0

I searched many questions here but seems no one is for the below question.


I am trying to create a block completion in Swift.

This is an optional variable closure in class X.

var onLogCompletion:((_ logThing:String) -> ())?

This is the function in class X.

func printerCompletion(currentLog:String) -> Void {
    //This is giving me an error:
    //Cannot call value of non-function type '((String) -> ())?'
    !(onLogCompletion(currentLog))
}

From class X, I want to call the function like this.

printerCompletion("New Log")

In a View Controller, I want to do stuff like this.

let objX = X()
objX.onLogCompletionm { (log) in 
    print(log)
}

That should print New Log in a View Controller file.

I have experience of doing this in Obj-C but not with Swift.

Please help to solve this and also if there's a better way of doing this.

Hemang
  • 26,840
  • 19
  • 119
  • 186
  • Can you show where you are calling this `printerCompletion` because if you are calling it from the `init` then your `onLogCompletionm` is not set and you are force wrapping when you call completion thats the reason you are getting nil, show more code – Nirav D May 15 '17 at 05:44

1 Answers1

1

Try this may this help you:

    var onLogCompletion:((_ logThing:String) -> ())? = nil


     func printerCompletion(currentLog:String) -> Void {
            self.onLogCompletion!(currentLog)
        }

     self.onLogCompletion  =  { (log) in
            print(log)
        }

you need to define block before calling of block other wise it will be nil

    objX.onLogCompletionm  = { (log) in
                            print(log)
                    }

   printerCompletion(currentLog: "New Log")

enter image description here

KKRocks
  • 8,222
  • 1
  • 18
  • 84
  • Thanks for the quick answer, that gave me an error: `fatal error: unexpectedly found nil while unwrapping an Optional value`. Is there any more decent way of doing this in Swift? – Hemang May 15 '17 at 05:36
  • As soon as I set `nil` for the closure, it works. I also require to checks ` func printerCompletion(currentLog:String) -> Void { if onLogCompletion != nil { onLogCompletion!(currentLog) } }` to fix the error. – Hemang May 15 '17 at 05:51
  • can you explain that which kind of that? – KKRocks May 15 '17 at 05:57