What are 'get' and 'set' in Swift?

I'm learning Swift and I'm reading The Swift Programming Language from Apple. I don't have any Objective-C background (only PHP, JavaScript, and others, but not Objective-C).

On page 24-25 I see this code:

//...Class definition stuff...


var perimeter: Double {
get {
return 3.0 * sideLength
}
set {
sideLength = newValue / 3.0
}
}


//...Class continues...

This part is not specified in the book, and I can't get what those are for.

What are get and set?

185786 次浏览

You should look at Computed Properties.

In your code sample, perimeter is a property not backed up by a class variable. Instead its value is computed using the get method and stored via the set method - usually referred to as getter and setter.

When you use that property like this:

var cp = myClass.perimeter

you are invoking the code contained in the get code block, and when you use it like this:

myClass.perimeter = 5.0

You are invoking the code contained in the set code block, where newValue is automatically filled with the value provided at the right of the assignment operator.

Computed properties can be read/write if both a getter and a setter are specified, or read-only if the getter only is specified.

The getting and setting of variables within classes refers to either retrieving ("getting") or altering ("setting") their contents.

Consider a variable members of a class family. Naturally, this variable would need to be an integer, since a family can never consist of two point something people.

So you would probably go ahead by defining the members variable like this:

class family {
var members: Int
}

This, however, will give people using this class the possibility to set the number of family members to something like 0 or 1. And since there is no such thing as a family of 1 or 0, this is quite unfortunate.

This is where the getters and setters come in. This way you can decide for yourself how variables can be altered and what values they can receive, as well as deciding what content they return.

Returning to our family class, let's make sure nobody can set the members value to anything less than 2:

class family {
var _members: Int = 2
var members: Int {
get {
return _members
}
set (newVal) {
if newVal >= 2 {
_members = newVal
} else {
println('error: cannot have family with less than 2 members')
}
}
}
}

Now we can access the members variable as before, by typing instanceOfFamily.members, and thanks to the setter function, we can also set it's value as before, by typing, for example: instanceOfFamily.members = 3. What has changed, however, is the fact that we cannot set this variable to anything smaller than 2 anymore.

Note the introduction of the _members variable, which is the actual variable to store the value that we set through the members setter function. The original members has now become a computed property, meaning that it only acts as an interface to deal with our actual variable.

A simple question should be followed by a short, simple and clear answer.

  • When we are getting a value of the property it fires its get{} part.

  • When we are setting a value to the property it fires its set{} part.

PS. When setting a value to the property, Swift automatically creates a constant named "newValue" = a value we are setting. After a constant "newValue" becomes accessible in the property's set{} part.

Example:

var A:Int = 0
var B:Int = 0


var C:Int {
get {return 1}
set {print("Recived new value", newValue, " and stored into 'B' ")
B = newValue
}
}


// When we are getting a value of C it fires get{} part of C property
A = C
A            // Now A = 1


// When we are setting a value to C it fires set{} part of C property
C = 2
B            // Now B = 2

A variable declares and is called like this in a class:

class X {
var x: Int = 3


}


var y = X()
print("value of x is: ", y.x)


//value of x is:  3


Now you want the program to make the default value of x more than or equal to 3. Now take the hypothetical case if x is less than 3: your program will fail.

So, you want people to either put in 3 or more than 3. Swift got it easy for you and it is important to understand this bit - it is an advanced way of dating the variable value, because they will extensively use it in iOS development. Now let's see how get and set will be used here.

class X {
var _x: Int = 3
var x: Int {
get {
return _x
}
set(newVal) {  // Set always take one argument
if newVal >= 3 {
_x = newVal // Updating _x with the input value by the user
print("new value is: ", _x)
}
else {
print("error must be greater than 3")
}
}
}
}


let y = X()
y.x = 1
print(y.x) // The error must be greater than 3
y.x = 8 // // The new value is: 8


If you still have doubts, just remember the use of get and set is to update any variable the way we want it to be updated. get and set will give you better control to rule your logic. It is a powerful tool, hence not easily understandable.