Swift has been out for a long time, and many projects have begun to be written with Swift, and now we're going to talk about
Use attribute Observer-Didset methods to note:
Didset method: Called immediately after the new value is set.
By chance, it is estimated that you do not know what is the use of it, in the actual project development, it is estimated that often encounter such a demand:
I have two variables, namely a,b. But there's a little bit of a special B variable that relies on a variable, which means that B must have a value.
can be set.
The use of it in the actual project, we can imagine, the use is still more. Just talk today about the precautions you need to use
Let's take a look at 3 examples:
I started by creating a student class that, when you call the Didset method, prints "The Didset method is called", and the code reads as follows:
Import Uikit
class Student:nsobject {
var name:string? {
Didset {
print (Didset method called)
}
}
override init () {
}
init (name:string) {
Self.name = name
}
func Testdidset () {
name = ' Ocean '
}
}
Then call the student class by clicking on the screen:
In the first case, the code is as follows:
Override Func Touchesbegan (_ Touches:set<uitouch>, with Event:uievent?) {Let
student = student ()
student.name = "Ocean"
}
Output results:
In the second case, the code is as follows:
Override Func Touchesbegan (_ Touches:set<uitouch>, with Event:uievent?) {Let
student = Student (name: "Ocean")
print (student.name)
}
Output results:
In the third case, the code is as follows:
Override Func Touchesbegan (_ Touches:set<uitouch>, with Event:uievent?) {Let
student = student ()
student.testdidset ()
}
Output results:
Do not, we can observe, the above three kinds of cases, why the second did not invoke the Didset method.
Can you find anything?
In the second case, the Init method is not invoked.
According to the official documents, we can draw the conclusion that:
The value is assigned at initialization time, and is not invoked by the Didset method.