简体   繁体   中英

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM