[SWIFT] Declare the model as an optional type

Introduction

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.

Preparation of model class

class Model {
    func model() {
        print("model")
    }
}

It defines a method called model. As an assumption, it is referenced and used from the controller class.

Preparation of 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()
    }
}

behavior

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.

Why declare a model as an optional type

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

Declare the model as an optional type
Let's understand the Optional (Wrapped) type!
Write a null case using the Optional type without using an if statement
Java Optional type
Refactor the Fat Model
null specifies the type
[Core ML] Incorporate an automatically generated ML model into the app