简体   繁体   English

Swift中的Objective-C块问题

[英]Trouble with Objective-C Block in Swift

I'm struggling to access a block from an Objective C file I found on Github and imported into my Swift project. 我正在努力访问在Github上找到并导入到我的Swift项目中的Objective C文件中的块。

Here is the Objective C block declaration in the .m file I imported: 这是我导入的.m文件中的Objective C块声明:

-(void)capture:(void (^)(LLSimpleCamera *camera, UIImage *image, NSDictionary *metadata, NSError *error))onCapture exactSeenImage:(BOOL)exactSeenImage;

Here is the block being called in the original Objective C Github sample project: 这是原始Objective C Github示例项目中调用的块:

[self.camera capture:^(LLSimpleCamera *camera, UIImage *image, NSDictionary *metadata, NSError *error) {
        if(!error) {

            [camera stop];

            ImageViewController *imageVC = [[ImageViewController alloc] initWithImage:image];
            [self presentViewController:imageVC animated:NO completion:nil];
        }
    } exactSeenImage:YES];

My Swift translation (done with autocomplete): 我的Swift翻译(使用自动完成功能):

self.camera?.capture({ (camera:LLSimpleCamera!, image:UIImage!, metadata:NSDictionary!, error:NSError!) -> Void in
        if error == nil {

            camera.stop()

            let imageVC = ImageCapturedViewController()
            self.presentViewController(imageVC, animated: NO, completion: nil)
        }
    }, exactSeenImage: true)

Xcode shows these two errors: Xcode显示以下两个错误:

'_??' '_ ??' is not convertible to 'Void' 不能转换为“无效”

'error type?' “错误类型?” is not convertible to 'Void' 不能转换为“无效”

It is because if the block does not have a return statement, the compiler uses the result of the last statement as the return value 这是因为如果该块没有return语句,则编译器将最后一条语句的结果用作返回值

Adding a return () as the last expression to the block fixes the problem 在块中添加return()作为最后一个表达式可解决此问题

this should do the trick :) 这应该可以解决问题:)

var aa:LLSimpleCamera = LLSimpleCamera()

swift have some converted NSDictionary to [NSObject:AnyObject], so the follow code can do the trick: swift将NSDictionary转换为[NSObject:AnyObject],因此以下代码可以解决问题:

aa.capture({ (camera:LLSimpleCamera!, image:UIImage!, obj:[NSObject:AnyObject]!, error:NSError!) -> Void in

}, exactSeenImage: true)

also, in swift, you can also omit the type of variable as follow: 此外,您还可以迅速省略变量的类型,如下所示:

aa.capture({ (camera, image, dict, error) -> Void in

}, exactSeenImage: true)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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