BluGeni
BluGeni

Reputation: 3454

objective C block to swift block

I am having trouble writing the method in objective C that calls a method in swift. I have all my headers set up correctly and simple methods are working but this I am not sure how to write the objective C side of this block.

my swift class

the function that i am trying to call:

func getOrders(completionHandler: (responseObject: NSString?) -> ()) {
    makeCall(completionHandler)
}

How I do it in swift (and what I want to do in Objective-C):

getOrders() { responseObject in
            // use responseObject and error here
            println("responseObject = \(responseObject); error = ")
            return
        }

and here is my attempt at objective-C block:

[billingService getOrders:completionHandler:^(NSString * responseObject) {
    NSLog(@"objective c callback: %@",responseObject);

}];

with the above I get use of undeclared identifier 'completionHandler'

I am just not sure how to make this work or construct a correct block in objective c.

Upvotes: 0

Views: 753

Answers (1)

jregnauld
jregnauld

Reputation: 1298

If you are not sure how to use Block in Objective C, take a look at this link: http://fuckingblocksyntax.com/ (http://goshdarnblocksyntax.com/ - SFW alternative)

To resume : As a local variable:

returnType (^blockName)(parameterTypes) = ^returnType(parameters) {...};

As a property:

@property (nonatomic, copy) returnType (^blockName)(parameterTypes);

As a method parameter:

- (void)someMethodThatTakesABlock:(returnType (^)(parameterTypes))blockName;

As an argument to a method call:

[someObject someMethodThatTakesABlock:^returnType (parameters) {...}];

As a typedef:

typedef returnType (^TypeName)(parameterTypes);
TypeName blockName = ^returnType(parameters) {...};

And this link if you need help to use block in swift : https://thatthinginswift.com/completion-handlers/

Objective-c

- (void)hardProcessingWithString:(NSString *)input withCompletion:(void (^)(NSString *result))block;

    [object hardProcessingWithString:@“commands” withCompletion:^(NSString *result){
        NSLog(result);
    }];
}

Swift

func hardProcessingWithString(input: String, completion: (result: String) -> Void) {
    …
    completion(“we finished!”)
}

hardProcessingWithString(“commands”) {
    (result: String) in
    println(“got back: (result)“)
}

So for your issue, it might be :

[billingService getOrders: ^(NSString * responseObject) {
    NSLog(@"objective c callback: %@",responseObject);

}];

Hope it helps!

Upvotes: 6

Related Questions