Sobes.tech
Junior — Middle

Millised konstruktoritüübid on klassis rakendatud ja kuidas nad erinevad?

sobes.tech AI

Vastus AI-lt

In the Swift class, the following types of constructors (initializers) are usually implemented:

  1. Default initializer (default initializer) — is created automatically if all properties have default values and there are no other initializers.

  2. Initializer with parameters (designated initializer) — the main initializer that initializes all properties of the class. Calling other initializers within the class is done via self.init.

  3. Convenience initializers (convenience initializer) — auxiliary initializers that call the designated initializer. They are used to simplify object creation with different sets of parameters.

Differences:

  • Designated initializers initialize all properties and call the superclass initializers.
  • Convenience initializers call other initializers of the same class and cannot directly initialize properties.

Example:

class Person {
    var name: String
    var age: Int

    // Designated initializer
    init(name: String, age: Int) {
        self.name = name
        self.age = age
    }

    // Convenience initializer
    convenience init(name: String) {
        self.init(name: name, age: 0) // call to designated
    }
}

Thus, constructors provide flexibility in initializing objects with different parameters and ensure the correct initialization of all properties.