Calling an objective-C typedef block from swift

I am trying to call a method from swift. The method is in singleton mode, written in objective-C

block in header file:

typedef void(^VPersonResultBlock)(Person *person, NSError *error);

- (void)askForMe:(VPersonResultBlock)block;

      

and here's the implementation of that method.

- (void)askForMe:(VPersonResultBlock)block
{
if (_me) block(_me,nil);
else {
    [Person getMeWithBlock:^(PFObject *person, NSError *error) {
        if (!error) {
            _me = (Person *)person;
            block(_me,nil);
        }

        else if (error) {
            block(nil,error);
        }
        else {
            NSDictionary *userInfo = @{
                                       NSLocalizedDescriptionKey: NSLocalizedString(@"Operation was unsuccessful.", nil),
                                       NSLocalizedFailureReasonErrorKey: NSLocalizedString(@"The operation failed to retrieve the user.", nil),
                                       NSLocalizedRecoverySuggestionErrorKey: NSLocalizedString(@"Check your network connection and try again", nil)
                                       };
            NSError *error = [[NSError alloc] initWithDomain:@"VisesAsyncErrorDomain" code:-10 userInfo:userInfo];
            block(nil,error);
        }
    }];
}
}

      

In Objective-C, I can call it and it auto-populates without confusion.

[[VDataStore instance] askForMe:^(Person *person, NSError *error) {
    // do things with myself that aren't strange
}];

      

Now let's say that I want to call the same method from swift. The bridge header is configured with the imported header file, but the fast wait is confusing.

VDataStore.askForMe(VDataStore)

      

This is what appears in the autocomplete options

(VPersonResultBlock!) -> Void askForMe(self: VDataStore)

      

what I was hoping for was autocomplete in a closure for this, and while it seems to display all the information correctly, what it expects doesn't line up with what objective-C understands.

How can I call this correctly with fast?

+3


source to share


1 answer


To directly translate the ObjC calling code to Swift -

VDataStore.instance().askForMe() {
    person, error in 
    // do things with myself that aren't strange
}

      



Your problem is that askForMe

is is an instance method, but you are accessing an object of the class VDataStore.askForMe

. Swift will provide you with a function object that takes an instance as input.

+5


source







All Articles