user2578850
user2578850

Reputation:

Setting property of objective-C class from Swift

I have a class MyClass subclassed from NSObject. It is written in Objective-C. It has a property with custom getter and setter:

    @interface MyClass : NSObject

        @property (getter = getIsBypassEnabled, setter = setIsBypassEnabled:) BOOL isBypassEnabled;

    @end

And both of these functions are defined in implementation:

    @implementation MyClass

    // Initializer and other stuff
    // ...

    -   (void) setIsBypassEnabled: (BOOL) newValue
    {
        _value = newValue;
    }

    -   (BOOL) getIsBypassEnabled
    {
        return _value;
    }

   @end

But when I try to set the property from Swift like:

let objcClass = MyClass()
objcClass.isBypassEnabled = true

I get an error 'isBypassEnabled' has been renamed to 'getIsBypassEnabled'. But I need to set the value, not get it!

Trying

objcClass.setIsBypassEnabled(true)

gives me an error that my class has no such member.

Declaring

-   (BOOL) getIsBypassEnabled;
-   (void) setIsBypassEnabled: (BOOL) newValue;

explicitly in .h file does not help either.

How do I resolve the issue? Thank you.

Upvotes: 2

Views: 1546

Answers (1)

Martin R
Martin R

Reputation: 539765

@interface MyClass : NSObject
@property (getter = getIsBypassEnabled, setter = setIsBypassEnabled:) BOOL isBypassEnabled;
@end

is mapped to Swift as

open class MyClass : NSObject {
    open var getIsBypassEnabled: Bool
}

so you can set the property actually with

let objcClass = MyClass()
objcClass.getIsBypassEnabled = true

I don't know if this mapping is intended or not, you might want to file a bug report.

You can also override the Swift mapping with

@interface MyClass : NSObject

@property (getter = getIsBypassEnabled, setter = setIsBypassEnabled:) BOOL isBypassEnabled
   NS_SWIFT_NAME(isBypassEnabled);
@end

and then

let objcClass = MyClass()
objcClass.isBypassEnabled = true

works as intended.

Upvotes: 3

Related Questions