将快速闭包(等效于块)分配给使用网桥访问的现有objective-c块 [英] Assigning a swift closure (block equivalent) to an existing objective-c block being accessed using a bridge

查看:86
本文介绍了将快速闭包(等效于块)分配给使用网桥访问的现有objective-c块的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Swift,想知道是否有一种方法可以将闭包分配给现有的Objective-C块.

I am using Swift and was wondering if there's a way I can assign a closure to an existing objective-c block.

fromObjC?.performBlock = {someVar in /*do something*/}

它给我一个错误无法分配给该表达式的结果".

It gives me an error "Cannot assign to the result of this expression".

推荐答案

所有指向Objective-C中对象的指针必须迅速为Optional,因为指针可以为nil.如果您知道该变量实际上永远不会为nil,则应使用隐式解包的可选内容"(TypeName!),这样就不必解包它.

All pointers to objects in objective-C must be Optional in swift because a pointer can be nil. If you know that the variable will never actually be nil, you should use Implicitly Unwrapped Optionals (TypeName!) so that you don't have to unwrap it.

所以

void(^performBlock)( UIStoryboardSegue* segue, UIViewController* svc, UIViewController* dvc )

成为:

{(segue : UIStoryboardSegue!, svc : UIViewController!, dvc : UIViewController!) in
    // Implementation
}

如果变量可能为nil,则应使用如下所示的常规Optional:

If the variable might be nil, you should use a normal Optional which would look like this:

{(segue : UIStoryboardSegue?, svc : UIViewController?, dvc : UIViewController?) in
    // Implementation
}

实际上,如果您将其分配给该属性,则甚至不必指定类型(可以推断出它们的类型):

And actually, if you are assigning it to that property, you don't even have to specify the types (they are inferred):

{(segue, svc, dvc) in
    // Implementation
}

这篇关于将快速闭包(等效于块)分配给使用网桥访问的现有objective-c块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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