2

I have a static method created on extension of Date. I am trying to call this method in Objective-C file. I am getting error as "No Known class for selector method name".

More detail:

In SWIFT 3.0

extension Date {
     static func  getDefaultFormattedDateStringFromDate(_ validToDate:Date) -> String? {

    }
}

In Objective-C

NSString *dateString = [NSDate getDefaultFormattedDateTimeStringFromDate:[NSDate date]];
Martin R
  • 529,903
  • 94
  • 1,240
  • 1,382
Raj
  • 67
  • 9

1 Answers1

2

struct Date is the "Swift overlay type" to the Foundation type NSDate (compare Swift 3: Date vs NSDate?) and unknown to Objective-C.

You'll have to define an extension to NSDate in order to be useable from Objective-C:

extension NSDate {
    static func  getDefaultFormattedDateStringFromDate(_ validToDate: Date) -> String? {
        // ...
    }
}

This is imported to Objective-C as

 @interface NSDate
 + (NSString * _Nullable)getDefaultFormattedDateStringFromDate:(NSDate * _Nonnull)validToDate;
 @end

Note that the parameter and return types (Date, String) are automatically bridged to the Foundation types (NSDate, NSString).


All this is unrelated to static (type) vs instance methods, and in your case it might be more "natural" to define an instance method:

extension NSDate {
    func defaultFormattedString() -> String? {
        // ...
    }
}

which is imported to Objective-C as

@interface NSDate
- (NSString * _Nullable)defaultFormattedString;
@end

and called as

NSString *dateString = [[NSDate date] defaultFormattedString];
Community
  • 1
  • 1
Martin R
  • 529,903
  • 94
  • 1,240
  • 1,382