This might sound dumb, but I can't figure out why programmers declare variables in Swift as follows:
class Person: NSObject {
var name: String { get }
}
Why is the keyword "get" used? Why is "set" missed? I thought we used them like this:
class Person: NSObject {
var name: String {
get {
// getter
}
set {
// setter
}
}
}
This might be a spam question, but I am interested in the theoretical definition of { get }
In swift, we use the var keyword to declare a variable. Swift uses variables to store and refer to values by identifying their name. Variables must be declared before they are used.
A getter in Swift allows access to a property, and a setter allows a property to be set. This post presents an overview of getters and setters, and examples of some Swift features related to getters and setters: Automatically Generated Getters and Setters. get Getter.
The variable total is declared with the let keyword. This is a value that can be changed.
Sentences such as var name: String { get }
are normally used in protocols not in classes. In a protocol it means that the implementation must have a variable of type String which should be at least read only (hence the get
). Had the curly brackets bit been { get set }
the variable would have been read write.
Actually as per Earl Grey answer, var name: String { get }
will not compile inside a class.
The first code example strictly speaking doesn't make sense. You do not declare variables like this in a class.. (You do it in a protocol like this.)
The second is an example of computed property,though the getter and setter implementation is missing. (it seems to be implied at least so I won't object about validity of the code example.)
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