Reputation: 48514
I am looking for a general solution to access:
@protocol
with readonly
propertiesSimilar 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
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 { /* ... */ } }
var _enabled:Bool = false
var enabled:Bool {
@objc(isEnabled) get {
return self._enabled
}
set(newValue){
_enabled = newValue
}
}
readonly
Objective-C Property in SwiftEither
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