Using NSDate category with Swift 3 Date type Using NSDate category with Swift 3 Date type objective-c objective-c

Using NSDate category with Swift 3 Date type


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.