JayVDiyk JayVDiyk - 2 months ago 12
Swift Question

Swift 3 Breaks My Objective C and Swift Handler/Closure Compatibility

SIAlertView is an external Objective C library I use in my project

In Swift 2.2 this line below compiles fine

class func showAlert(title title : String, message: String, confirmHandler: (SIAlertView!) -> Void) {

...
alertView.addButtonWithTitle(OK_TITLE, type: SIAlertViewButtonType.Default, handler: confirmHandler);
alertView.show();
}


But now in Swift 3 there is an error message saying

enter image description here

From the Objective C Class I find that

SIAlertView.h

@class SIAlertView;
typedef void(^SIAlertViewHandler)(SIAlertView *alertView);


SIAlertView.m

- (void)addButtonWithTitle:(NSString *)title type:(SIAlertViewButtonType)type handler:(SIAlertViewHandler)handler
{
SIAlertItem *item = [[SIAlertItem alloc] init];
item.title = title;
item.type = type;
item.action = handler;
[self.items addObject:item];
}


Could anyone explain this please? Because it previously works fine in Swift 2.2

Answer

Change This

class func showAlert(title title : String, message: String, confirmHandler: (SIAlertView!) -> Void)

To This

class func showAlert(title title : String, message: String, confirmHandler: (SIAlertView?) -> Void)

In Objective C, this parameters could be nil, therefore we must declare it as optional.

Comments