Reputation: 1329
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 ?
Upvotes: 1
Views: 868
Reputation: 17721
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]];
Upvotes: 1