Junior — Middle
Mis on objektide initsialiseerimise protsess klasside sees ja kuidas see realiseeritakse?
sobes.tech AI
Vastus AI-lt
Object initialization within classes is the process of assigning initial values to the object's properties at the time of its creation. In Swift, this is done using an initializer, a special method init that is called when creating an instance of the class.
Example of an initializer in a class:
class User {
var name: String
var age: Int
init(name: String, age: Int) {
self.name = name
self.age = age
}
}
let user = User(name: "Ivan", age: 30)
Here, init ensures that all properties name and age are initialized before the object is used. It is important that all properties are initialized before the initializer completes, otherwise the compiler will generate an error.