Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I expose Swift default parameter values to Objective-C?

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?

like image 678
Adam S Avatar asked Feb 03 '16 18:02

Adam S


People also ask

Can you assign the default values to a function parameters?

Default parameter in JavascriptThe default parameter is a way to set default values for function parameters a value is no passed in (ie. it is undefined ). In a function, Ii a parameter is not provided, then its value becomes undefined . In this case, the default value that we specify is applied by the compiler.

Can you assign the default values to a function parameters True False?

Yes, it is correct that you can assign a default value to the parameter before calling the function, which results in you not needing to pass an argument when calling the function. The default parameter is however always overridden if you pass a value to the function.


1 Answers

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.

like image 151
ssrobbi Avatar answered Sep 22 '22 11:09

ssrobbi