简体   繁体   中英

Assigning a swift closure (block equivalent) to an existing objective-c block being accessed using a bridge

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".

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.

So

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

becomes:

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

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
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM