Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using NSDate category with Swift 3 Date type

I have an Obj-C category on NSDate and I am trying to use the functions in that category with Swift's Date structure.

Is there a clean way to do that without having to cast every time or having to create NSDate instance from Date or some ugly other hack?

Or am I stuck with having to define my objects as NSDate instead of Date?

Apple mentions here that

The Swift overlay to the Foundation framework provides the Date structure, which bridges to the NSDate class. The Date value type offers the same functionality as the NSDate reference type, and the two can be used interchangeably in Swift code that interacts with Objective-C APIs. This behavior is similar to how Swift bridges standard string, numeric, and collection types to their corresponding Foundation classes.

, so my question is how can I access the extra functions in my NSDate category with my Date objects with clean minimal code?

For reference, I am using Swift 3.

like image 347
static0886 Avatar asked Sep 26 '16 14:09

static0886


1 Answers

Swift's 3 bridged types are implemented via an internal reference to their corresponding Objective-C object. So, similar to the "composition over inheritance" principle, you can declare the methods you're interested in, in Swift, and simply forward the call.

For example, if you have the following method in Objective-C:

@interface NSDate(MyAdditions)
- (NSString*)myCustomNicellyFormattedDate;
@end

you could add an extension to Date that simply casts and forwards:

extension Date {
    var myCustomNicellyFormattedDate: String { 
        return (self as NSDate).myCustomNicellyFormattedDate()
    }
}

This approach has the advantage of having the method available in both Objective-C and Swift, with little overhead and maintenance troubles. And most important, without code duplication.

like image 111
Cristik Avatar answered Oct 13 '22 20:10

Cristik