Den
Den

Reputation: 3561

Convert Objective-C block to Swift closure

I want to convert block to closure, but I can't figure out how. I don't know what's the problem.

Objective-C:

// monthBlock type
typedef NSString *(^JTCalendarMonthBlock)(NSDate *date, JTCalendar *jt_calendar);

// Block
self.calendar.calendarAppearance.monthBlock = ^NSString *(NSDate *date, JTCalendar *jt_calendar){
    return @"";
};

Swift:

// Swift closure
self.calendar.calendarAppearance.monthBlock = {(date:NSDate, jt_calendar:JTCalendar) -> NSString in
    return "" as NSString
}  

produces error:

Error: Cannot assign a value of type '(NSDate, JTCalendar) -> NSString' to a value of type 'JTCalendarMonthBlock!'

Upvotes: 8

Views: 3466

Answers (1)

Rob
Rob

Reputation: 437392

Your parameter types don't quite match up. You can either do:

self.calendar.calendarAppearance.monthBlock = { (date: NSDate!, jt_calendar: JTCalendar!) -> String! in
    return ""
}

Or, more simply:

calendar.calendarAppearance.monthBlock = { date, jt_calendar in
    return ""
}

I assume JTCalendar is not your own class. If it was, you might consider auditing it, adding nullability annotations to make it explicit whether these parameters could be nil or not. In the absence of those annotations, Swift has no way of knowing whether these are nullable or not, so it interprets these parameters as implicitly unwrapped optionals.

Upvotes: 16

Related Questions