Can someone clarify the role of initializers please I'm kinda confused

What is the difference between init and a method? Can someone clarify this with a simple example please

init is a special method that ensures that your data structure (whether a class or a struct) is ready for use by making sure that every stored property has a value and taking care of any other setup that is required.

Here is an example from the official docs:

struct Celsius {
    var temperatureInCelsius: Double
    init(fromFahrenheit fahrenheit: Double) {
        temperatureInCelsius = (fahrenheit - 32.0) / 1.8
    }
    init(fromKelvin kelvin: Double) {
        temperatureInCelsius = kelvin - 273.15
    }
}
let boilingPointOfWater = Celsius(fromFahrenheit: 212.0)
// boilingPointOfWater.temperatureInCelsius is 100.0
let freezingPointOfWater = Celsius(fromKelvin: 273.15)
// freezingPointOfWater.temperatureInCelsius is 0.0

You can see that the struct's temperatureInCelsius property is stored, as its name suggests, in degrees Celsius. But what if you have the temperature in some other scale? Well, you can use one of the initializers and pass in a temperature in Fahrenheit or Kelvin. Those init methods ensure that the data passed in is converted to the proper scale before being stored in the struct.

init methods aren’t always necessary, though. If you have a struct that needs no extra work, just assigning property values, you can use its member-wise initializer, which is synthesized for free by the compiler. So something like this doesn’t need an explicit init method:

struct Person {
    let name: String
    let age: Int
}

// this init is provided for free by the compiler
let person1 = Person(name: "John Doe", age: 42)

Classes, on the other hand, always need an init, unless they inherit one from their super class and don’t need to do any additional work.

Methods are functions that are part of a given data structure. They perform some kind of work and can use the properties and other methods of the data structure. Here’s an example:

struct Person {
    let name: String
    let age: Int

    func greet() {
        print("Hello, \(name)!")
    }
}

// this init is provided for free by the compiler
let person1 = Person(name: "John Doe", age: 42)
person1.greet()
// prints "Hello, John Doe!"

Hope this helps.

1 Like

Thank you for clarifying is makes a bit more sense now I just need to wrap my head around this