21

Say I have some Swift class with methods I'd like to expose to Objective-C:

@objc(Worker) class Worker : NSObject {
    func performWork(label: String = "Regular Work") {
        // Perform work
    }
}

I can call this in two ways:

Worker().performWork()
Worker().performWork("Swift Development")

However, when called from Objective-C, I do not get the "default" version of this method - I must supply a label:

[[[Worker alloc] init] performWork:@"Obj-C Development"];

See the definition from my AppName-Swift.h header below:

SWIFT_CLASS_NAMED("Worker")
@interface Worker : NSObject
- (void)performWork:(NSString * __nonnull)label;
- (nonnull instancetype)init OBJC_DESIGNATED_INITIALIZER;
@end

I would expect to see a method with this signature:

- (void)performWork;

I realise ObjC doesn't support default parameter values, but my assumption was that the Swift default values simply generate additional Swift functions with trivial implementations calling the "real" function (i.e. they're syntactic sugar hiding the typical implementation we'd use in Obj-C).

Is there any way to expose this default value to Objective-C? If not, can anyone point me to any documentation on why this isn't available?

Community
  • 1
  • 1
Adam S
  • 16,144
  • 6
  • 54
  • 81
  • 1
    I doubt you'll get a better reason than "Apple is too busy to get to it". At WWDC last year, all the talks were about Swift. ObjC only get 2 new features: nullability markers and generics – Code Different Feb 03 '16 at 19:55

1 Answers1

6

The answer is no, there is currently no way to expose that.

It is however, being considered for Swift 3.0 (see the proposal here)

EDIT: This is incorrect as pointed out by Adam S.

ssrobbi
  • 496
  • 1
  • 5
  • 15
  • 1
    From what I read in that proposal, it's considering utilising Swift default parameters when exposing Obj-C APIs, allowing you to skip things that can be easily defaulted when calling Obj-C APIs _from Swift_. This is great, however I'm looking for the other direction - unless I'm misreading or overlooking something there. – Adam S Feb 04 '16 at 19:04
  • [This is the section I'm referring to](https://github.com/apple/swift-evolution/blob/master/proposals/0005-objective-c-name-translation.md#add-default-arguments) which describes the changes you could make to your Swift code to take advantage of that potential feature. – Adam S Feb 04 '16 at 19:05
  • @AdamS You are very right. I skimmed the title in the mailing list and made assumptions (I should have taken the title of that proposal into consideration) – ssrobbi Feb 04 '16 at 19:20
  • 3
    So what... is this still not possible ? – Renetik Sep 16 '19 at 07:29