Kamilski81
Kamilski81

Reputation: 15107

How do I call an Swift method with a closure from Objective-c?

I have the following Swift method:

public func login(userLogin: String, userPassword: String, completion:@escaping (_ result: Result<Data, PZError>) -> ())

And I would like to call it from Objective-C but can't figure out the closure portion:

[apiController loginWithUserLogin:userLogin userPassword:password completion:???];

What would my completion code look like in Objective-C?

Upvotes: 0

Views: 71

Answers (1)

battlmonstr
battlmonstr

Reputation: 6280

It is not possible to call such a method directly from Objective-C.

If you Result type is an enum with non-trivial "case" objects or a struct, it won't work, because Objective-C doesn't support value types. Also Objective-C doesn't support generic types like Result<T>.

One way to fix would be to make a wrapper, i.e. write a second method in Swift that adapts the types:

func login(userLogin: String, userPassword: String,
    completion: @escaping (_ resultData: Data?, _ resultError: NSError?) -> Void)

In this method you would call your original login, and in the internal completion callback unwrap your Result into Data and NSError (converting from PZError), and pass 'em the caller's completion block.

Upvotes: 1

Related Questions