When I was studying the MVC architecture, I had code that defined instance variables as optional types. I will write about the reason and behavior. Comments are welcome.
class Model {
func model() {
print("model")
}
}
It defines a method called model. As an assumption, it is referenced and used from the controller class.
The instance variable model is defined with theModel?Type.
methodOfModel is a method that performs the model method of the Model class.
class Controller {
var model: Model? {
didSet {
print("changed")
}
}
func methodOfModel() {
model?.model()
}
}
let controller = Controller()
print("model is\(controller.model)")//model isnil
controller.methodOfModel()//Not executed at this point
controller.model = Model() //changed
print("model is\(controller.model)")//model isOptional(Page_Contents.Model)
controller.methodOfModel()//model
The first line instantiates Controller.
The second line confirms that controller.model is nil.
The third line confirms that controller.method is not executed.
The 4th line puts Model () in controller.model. Now that the value of model has changed, didSet is executed.
The fifth line says the same thing as the second line. However, you can see that model is not nil.
The same thing is written on the 6th line as on the 3rd line. However, the model of the Model class is executed.
From here, I will first declare that the color of the person who writes is strong.
let model = Model()
If you do, the class-to-class bond will be stronger. Isn't it one of the aims to have the classes instantiated from the outside in order to loosely connect them?
Recommended Posts