简体   繁体   English

Swift等效于Objective-C代码块?

[英]Swift Equivalent of Objective-C Block?

I have the following Objective-C syntax: 我有以下Objective-C语法:

@property (nonatomic, copy) void(^cropBlock)(UIImage *image);

- (void)cropAction {
    if (self.cropBlock) {
        self.cropBlock(self.imageScrollView.capture);
    }
}

I need the Swift equivalent syntax and I tried: 我需要使用Swift的等效语法,并尝试了以下操作:

var cropBlock: (UIImage) -> Void 

private func cropAction() {
    if (self.cropBlock != nil) {
        self.cropBlock(self.imageScrollView.capture);
    }
}

But I got the error: 但是我得到了错误:

(UIImage) -> Void' is not convertible to 'UInt8

What is the correct Swift representation? 正确的Swift表示是什么?

var cropBlock: ((UIImage?) -> Void)?

private func cropAction() {
    self.cropBlock?(self.imageScrollView.capture())
}

If cropBlock can be nil , it should be Optional . 如果cropBlock可以为nil ,则应该为Optional

And also if self.imageScrollView.capture can be nil , the first parameter of cropBlock should be Optional . 并且如果self.imageScrollView.capture可以是nil ,第一个参数cropBlock应该是Optional

self.cropBlock?(self.imageScrollView.capture()) is a shortcut of: self.cropBlock?(self.imageScrollView.capture())是以下操作的快捷方式:

if let fn = self.cropBlock {
    fn(self.imageScrollView.capture())
}

Define it as a typealias in Swift: 在Swift中将其定义为typealias:

typealias CropBlock = (image : UIImage) -> ()

For more information you can read the official documentation for typealias here . 有关更多信息,您可以在此处阅读typealias的官方文档。

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

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