简体   繁体   中英

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 (ie 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?

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.

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