Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!'

like image 498
Den Avatar asked Apr 20 '15 09:04

Den


1 Answers

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.

like image 113
Rob Avatar answered Oct 02 '22 20:10

Rob