Graeme Graeme - 5 months ago 42
iOS Question

How to convert an Objective-C Block into a Swift Closure?

I have the following Objective-C block assignment example from Github dzenbot/DZNPhotoPickerController that I am struggling to convert to Swift. Controller is a UIImagePickerController.

controller.finalizationBlock = ^(UIImagePickerController *picker, NSDictionary *info) {

UIImage *image = info[UIImagePickerControllerEditedImage];
weakSelf.imageView.image = image;

// Dismiss when the crop mode was disabled
if (picker.cropMode == DZNPhotoEditorViewControllerCropModeNone) {
[weakSelf dismissController:picker];
}
};


I have tried the following, but cannot figure out where I am going wrong.

controller.finalizationBlock = { (picker: UIImagePickerController, info: NSDictionary) -> UIImagePickerControllerFinalizationBlock! in
var image = UIImagePickerControllerEditedImage(info)
imageView.image = image

// Dismiss when the crop mode was disabled
if (picker.cropMode == .None) {
dismissEditor(picker)
}
}


The error I get is:


"Cannot assign value of type '(UIImagePickerController, NSDictionary) -> UIImagePickerControllerFinalizationBlock!' to type 'UIImagePickerControllerFinalizationBlock!'

Answer

The Objective-C block does not return anything, so the closure for the same should look like this:

controller.finalizationBlock = { (picker, info) in
        var image = UIImagePickerControllerEditedImage(info)
        imageView.image = image

        // Dismiss when the crop mode was disabled
        if (picker.cropMode == .None) {
            dismissEditor(picker)
        }
    }
Comments