What is the equivalent of the following Objective-C code in Swift?
@property (nonatomic, assign, getter = isOpen) BOOL open;
Specifically, how does one declare a variable in Swift to synthesize the getter with a custom name?
Furthermore, how can you subsequently override the implementation of the getter and setter?
Getters and setters are essential in any language. Here, in Swift, they are applied to computed properties that do not have access to their own storage, so need to be derived from other properties. They certainly will be useful for future projects…
Objective-C properties offer a way to define the information that a class is intended to encapsulate. As you saw in Properties Control Access to an Object's Values, property declarations are included in the interface for a class, like this: @interface XYZPerson : NSObject.
What are Getters and Setters? Getters: These are the methods used in Object-Oriented Programming (OOPS) which helps to access the private attributes from a class. Setters: These are the methods used in OOPS feature which helps to set the value to private attributes in a class.
Your assumption was close, but a few things could be changed. I will try to help you get as close as possible to the Objective-C version.
First of all, the nonatomic
and assign
are irrelevant in swift. That leaves us with
@property (getter = isOpen) BOOL open;
Since properties in swift are just instance variables, the swift translation would be as follows.
var open:Bool
Although this has the same basic functionality as the Objective-C version, it is lacking the named getter (isOpen
). Unfortunately, there is no direct translation to swift for this (yet). You could use a custom getter and setter.
var open:Bool {
get {
// custom getter
}
set {
// custom setter
}
}
A rather crude work around would be to make another function literally called isOpen
that would act as a getter.
func isOpen() -> Bool { return self.open }
In conclusion, what you are asking is only slightly possible, but hopefully in later releases of swift can become a reality.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With