Skip to content

Instantly share code, notes, and snippets.

@sveinhal
Created July 2, 2015 10:50
Show Gist options
  • Save sveinhal/49bd95d11fb5ac8dcd26 to your computer and use it in GitHub Desktop.
Save sveinhal/49bd95d11fb5ac8dcd26 to your computer and use it in GitHub Desktop.
How to implement an Obj-C protocol with custom getter name in Swift
class SomeClass: SomeProtocol {
private var _enabled: Bool = false
var enabled: Bool {
@objc(isEnabled) get { return _enabled }
set { _enabled = newValue }
}
}
@protocol SomeProtocol <NSObject>
@property (nonatomic, getter=isEnabled) BOOL enabled;
@end
@sveinhal
Copy link
Author

sveinhal commented Jul 2, 2015

You can expose a Swift property or function to the Objective-C runtime with a different name, using the @objc(name) attribute. However, exposing a different name for only the getter, requires that you explicitly define a setter and getter individually, which again requires that you use another (private) variable for backing.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment