从Swift调用Objective-C typedef块 [英] Calling objective-C typedef block from swift

查看:97
本文介绍了从Swift调用Objective-C typedef块的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从Swift调用方法. 该方法以用Objective-C编写的单例形式

I'm trying to call a method from swift. The method is in a singleton written in objective-C

头文件中的块:

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

- (void)askForMe:(VPersonResultBlock)block;

这是该方法的实现.

- (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);
        }
    }];
}
}

在Objective-C中,我可以称之为它,它会自动完成而不会引起混乱.

In Objective-C, I can call this and it autocompletes without confusion.

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

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

Now let's say I want to call the same method from swift. The bridging header is setup, with the header file imported, but swift's expectation is confusing.

VDataStore.askForMe(VDataStore)

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

This is what shows up in the autocomplete options

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

我希望的是将其自动完成为一个闭包,尽管看上去正确地看到了所有信息,但它所期望的并没有与Objective-C似乎理解的一致.

what I was hoping for, was for this to autocomplete into a closure, and although it appears to see all of the information correctly, what it's expecting isn't lining up with what objective-C seems to understand.

如何快速调用此名称?

推荐答案

直接将您的ObjC调用代码转换为Swift is

Directly translate your ObjC calling code to Swift is

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

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

Your problem is that askForMe is instance method but you are accessing from class object VDataStore.askForMe. Swift will give you a function object that takes an instance as input.

这篇关于从Swift调用Objective-C typedef块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆