Lucifer Lucifer - 6 months ago 7
Swift Question

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

this might sound stupid, but I can't figure out why do programmers declare variables in Swift as follows:

class Person: NSObject {
var name: String { get }
}


Why is the keyword "get" used? Why is "set" missed? Aren't they supposed to be used as follows:

class Person: NSObject {
var name: String {
get {
// getter
}
set {
// setter
}
}
}


I guess this is a spam question, but I am interested in the theoretical definition of { get }

Answer

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.

Comments