从swift调用objective-C typedef块

dom*_*all 3 closures objective-c ios objective-c-blocks swift

我正试图从swift调用一个方法.该方法是用Objective-C编写的单例

头文件中的块:

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

- (void)askForMe:(VPersonResultBlock)block;
Run Code Online (Sandbox Code Playgroud)

这是该方法的实现.

- (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);
        }
    }];
}
}
Run Code Online (Sandbox Code Playgroud)

在Objective-C中,我可以调用它,它可以自动完成而不会产生混淆.

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

现在让我们说我想从swift调用相同的方法.设置了桥接头,导入了头文件,但swift的期望令人困惑.

VDataStore.askForMe(VDataStore)
Run Code Online (Sandbox Code Playgroud)

这是自动填充选项中显示的内容

(VPersonResultBlock!) -> Void askForMe(self: VDataStore)
Run Code Online (Sandbox Code Playgroud)

我希望的是,这是为了自动完成一个闭包,虽然它看起来正确地看到了所有的信息,它期待的是没有排列什么目标-C似乎理解.

如何从swift中正确调用?

Bry*_*hen 5

直接将你的ObjC调用代码翻译成Swift

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

您的问题是askForMe实例方法,但您正在从类对象访问VDataStore.askForMe.Swift将为您提供一个以实例作为输入的函数对象.