Named Objects Obj-C Getters and Setters in Swift

I am looking for a general access solution:

  • Obj-C named getters properties and named property definition tools from Swift
  • Corresponds to Objective-C @protocolwith readonlyproperties

Similar to Creating an Objective-C equivalent Getter and Setter in Swift , which is closed but does not give a satisfactory answer.


Objective-C Swift Example:

I have an Objective-C protocol defined with two problematic properties, one with a custom getter isEnabled, and the other with a private installer 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 work:

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

and does not:

var isEnabled:Bool {
    get { }
    set { }
}
+4
1

documentation:

@objc (< # name # > ), Objective-C , . , , , getter isEnabled Objective-C :

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

Objective-C Getter Swift

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

readonly Objective-C Swift

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

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

self._exists , .

+5

Source: https://habr.com/ru/post/1606395/


All Articles