1

Hello is it possible to make a callback like such? I want to pass a function as a parameter to be able run the callback function after some task is finished.

class ConnectBLE { var callBackFunc: ()->() init(callFunc: @escaping () -> ()){ callBackFunc = callFunc } func runCallBackFunc() { callBackFunc() } } class DelegateARC { private let object = ConnectBLE(callFunc: RaspakHC05) func RaspakHC05() { print("hello from a callback") } } 

But I'm having an error. Cannot convert value of type '(DelegateARC) -> () -> ()' to expected argument type '() -> ()'

3
  • Why would the print message come out? There is no call to the callback? Commented Jun 13, 2017 at 17:26
  • 1
    @Rob it does not compile. Commented Jun 13, 2017 at 17:29
  • 2
    It doesn't work because you can't reference self in a non-lazy property initializer, as they are run before your object is initialized. Try: private lazy var object: ConnectBLE = ConnectBLE(callFunc: self.RaspakHC05) Commented Jun 13, 2017 at 17:30

3 Answers 3

3

You cannot run non-lazy code on the top level of the class which requires self (RaspakHC05).

Apart from that you have to call runCallBackFunc() in ConnectBLE somewhere to execute the closure.

You could do (in a Playground)

class ConnectBLE { var callBackFunc: ()->() init(callFunc: @escaping () -> ()){ callBackFunc = callFunc } func runCallBackFunc() { callBackFunc() } } class DelegateARC { init() { ConnectBLE(callFunc: RaspakHC05).runCallBackFunc() } func RaspakHC05() { print("hello from a callback") } } DelegateARC() // prints "hello from a callback" 
Sign up to request clarification or add additional context in comments.

Comments

2

Another way (use Optional to delay giving object its real value until initialization has otherwise fully taken place):

class ConnectBLE { var callBackFunc: ()->() init(callFunc: @escaping () -> ()){ callBackFunc = callFunc } func runCallBackFunc() { callBackFunc() } } class DelegateARC { private var object : ConnectBLE! //* init() { self.object = ConnectBLE(callFunc: RaspakHC05) // * } func RaspakHC05() { print("hello from a callback") } } 

Comments

1

You are trying to pass a function instead a closure. You have to use a closure and lazy instantiation to make it work:

class DelegateARC { private lazy var object: ConnectBLE = { return ConnectBLE(callFunc: self.RaspakHC05) }() var RaspakHC05: () -> () { return { print("hello from a callback") } } } 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.