Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating an Objective-C equivalent Getter and Setter in Swift

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?

like image 899
mike Avatar asked Jun 10 '14 21:06

mike


People also ask

Should I use getters and setters in Swift?

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…

What is a property in Objective C?

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 is getter and setter properties?

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.


1 Answers

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.

like image 199
Brian Tracy Avatar answered Oct 02 '22 00:10

Brian Tracy