SwiftArchitect
SwiftArchitect

Reputation: 48514

Named Obj-C Property Getters and Setters in Swift

I am looking for a general solution to access:

  1. Obj-C named property getters and named property setters from Swift
  2. Conform to an Objective-C @protocol with readonly properties

Similar to Creating an Objective-C equivalent Getter and Setter in Swift, which is closed, yet does not offer a satisfying answer.


Objective-C to Swift Properties Example:

I have an Objective-C protocol defined with two problematic properties, one with a custom getter isEnabled and another with a private setter exists.

@protocol SomeProtocol <NSObject>
@property (nonatomic, assign, getter = isEnabled) BOOL enabled;
@property (nonatomic, readonly) BOOL exists;
@end

How can I access these Objective-C properties from Swift?

This does not seem to work:

func isEnabled() -> Bool { return self.enabled }

and neither does:

var isEnabled:Bool {
    get { }
    set { }
}

Upvotes: 4

Views: 4517

Answers (1)

SwiftArchitect
SwiftArchitect

Reputation: 48514


Straight from the documentation:

Use the @objc(<#name#>) attribute to provide Objective-C names for properties and methods when necessary. For example, you can mark a property called enabled to have a getter named isEnabled in Objective-C like this:

SWIFT

var enabled: Bool { @objc(isEnabled) get { /* ... */ } }

Named Objective-C Getter Property in Swift

var _enabled:Bool = false
var enabled:Bool {
    @objc(isEnabled) get {
        return self._enabled
    }
    set(newValue){
        _enabled = newValue
    }
}

readonly Objective-C Property in Swift

Either

var _exists:Bool = false
private(set) var exists:Bool {
    get{
        return self._exists
    }
    set(newValue){
        self._exists = newValue
    }
}

or

var _exists:Bool = false
var exists:Bool {
    get{
        return self._exists
    }
}

and access self._exists directly since there is no setter.

Upvotes: 6

Related Questions