2

I need to call a swift function from objective-c. This needs to have a callback (that will be executed from obj-c)

@objc public func getTokens(forAuthentificationCode auth_code : String, completion: ()->()? )

I get "Method cannot be marked @objc because the parameter..." How to make a function with a completion block that can be used from objective-c?

user426132
  • 1,341
  • 4
  • 13
  • 28
  • Might be Related: https://stackoverflow.com/questions/40904250/objective-c-call-swift-function/40905352#40905352 – Ahmad F Mar 02 '18 at 13:35
  • 2
    I think you wanted to write `completion: (()->())?` - see the extra level of parentheses around the closure definition – Cristik Mar 02 '18 at 13:36
  • ()->()? is a closure with no arguments and that returns an optional `Void`, and a `Void?` (aka ()?) is not compatible with Objective-C – Cristik Mar 02 '18 at 13:37
  • The extra level of parentheses fixed it thanks! – user426132 Mar 02 '18 at 13:51

1 Answers1

3

You declared the completion parameter as ()->()?, which translates to a closure with no parameters and that returns a Void?. Objective-C supports optionals only for class arguments, thus the completion block is not Objective-C compatible.

I think however that you intended to declare the whole closure as optional, in order to allow callers to pass nil, in that case you need to wrap the closure definition into another set of parentheses: completion: (() -> Void)?. I changed the return type from () to Void for better readability, as Void is just an alias for ().

Cristik
  • 30,989
  • 25
  • 91
  • 127