将 Objective-C 块转换为 Swift 闭包

Convert Objective-C block to Swift closure

我想将块转换为闭包,但不知道如何操作。不知道是什么问题

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
}  

产生错误:

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

您的参数类型不太匹配。你可以这样做:

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

或者,更简单地说:

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

我假设 JTCalendar 不是你自己的 class。如果是,您可能会考虑审核它,添加 nullability annotations 以明确这些参数是否可以是 nil。在没有这些注释的情况下,Swift 无法知道它们是否是 nullable,因此它将这些参数解释为隐式解包的可选参数。