1

I have a swift class, A, which accepts delegates. I have another swift class, B, which implements the delegates. Now the object of A is instantiated from objective-c code.

I need to pass the function g as a parameter to the function f. How do I do this ?

Class which accepts a delegate :

class A {
    func f(_ e: String, d D: @escaping ((String)->Void)) {
        D() // Call the function that we recieved as a parameter
    }
}

Class which implements the delegate :

class B {
    func g(_ m: String) {
        // Implementation.
    }
}

How things are called from obj-c :

A *a;
B *b;

[a f:@"someString" d:b.g] // How to pass the swift function as a parameter ?
3
  • It looks like closure and it will be treat as block in Obj c Commented Nov 24, 2017 at 8:07
  • You need just pass block that calls b's g. Commented Nov 24, 2017 at 8:11
  • @Cy-4AH I don't know how to do that. I am a newbie in swift and obj-c. Commented Nov 24, 2017 at 8:13

1 Answer 1

1

You should encapsulate the call to g into a Objective-C block like this:

[a f:@"someString" d:^(NSString *s) {
    [b g:s];
}];

If you also want keeping the parameter function for d variable, you need a dictionary of closures:

A *a = ...;
B *b = ...;
NSDictionary *myFunctions = @{
    'g': ^(NSString *s) { [b g:s]; },
    'h': ^(NSString *s) { [b h:s]; }
};
NSString *functionName = ...;

[a f:@"someString" d:myFunctions[functionName]];
Sign up to request clarification or add additional context in comments.

2 Comments

I am not trying to call g. I am trying to pass the function g as a parameter to f.
Yes, I understood this but you can't create a Swift-like function from an Objective-C method directly. The closure eliminates this problem. My code doesn't call g. It creates a closure to call g.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.