Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do we use the keyword "get" in Swift variables declaration?

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 }

like image 634
Lucifer Avatar asked May 15 '16 07:05

Lucifer


People also ask

Which keyword is used to declare a variable Swift?

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.

What is get in Swift?

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.

What is a keyword used when declaring a variable?

The variable total is declared with the let keyword. This is a value that can be changed.


2 Answers

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.

like image 155
gabriel_101 Avatar answered Sep 24 '22 17:09

gabriel_101


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.)

like image 26
Earl Grey Avatar answered Sep 22 '22 17:09

Earl Grey