Using NSDate category with Swift 3 Date type
Asked Answered
N

1

13

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.

Natasha answered 26/9, 2016 at 14:55 Comment(1)
To use that NSDate Objective-C category, you have to cast your Date object to NSDate. Or you can rewrite your category as a Swift extension to Date.Nautch
S
10

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.

Shiller answered 5/1, 2017 at 6:56 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.