iosswift3swift-block

How to write a block to return value from one class to another?


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.


Solution

  • 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