Search code examples
swiftviewcontrollerinitializer

No need for initializer for optional properties inside Swift class


Why we don't need initializer for optional properties inside any class in ViewController.swift files?

class SpareParts {
    var wheels: Int8?
    var engine: String?
}

But if class's properties are non-optional we immediately need an init() method:

enter image description here


Solution

  • Optional Property Types :

    If your custom type has a stored property that is logically allowed to have “no value”—perhaps because its value cannot be set during initialization, or because it is allowed to have “no value” at some later point—declare the property with an optional type. Properties of optional type are automatically initialized with a value of nil, indicating that the property is deliberately intended to have “no value yet” during initialization.

    For Example :

    class SurveyQuestion {
        var text: String?
        init(text: String) {
            self.text = text
        }
        func ask() {
            print(text)
        }
    }
    
    let cheeseQuestion = SurveyQuestion(text: "Do you like cheese?")
    cheeseQuestion.ask()
    // Prints "Do you like cheese?"
     let cheeseQuestion1 = SurveyQuestion()
    cheeseQuestion.ask() 
    // Prints nil