简体   繁体   中英

Swift Equivalent of Objective-C Block?

I have the following Objective-C syntax:

@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:

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?

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

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

If cropBlock can be nil , it should be Optional .

And also if self.imageScrollView.capture can be nil , the first parameter of cropBlock should be Optional .

self.cropBlock?(self.imageScrollView.capture()) is a shortcut of:

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

Define it as a typealias in Swift:

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

For more information you can read the official documentation for typealias here .

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