Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

iOS

When do I need to use initialiser method in a swift? When it is necessary when it is considered to be an option.

When do I need to use initialiser method in a swift? When it is necessary when it is considered to be an option. I know that in Structure it is automatically crated and in classes I need to creat it. But i can not understand when do I need to create them ?? Sorry I am a bit confused. Does anybody has any explanation?

Initializer methods are the methods inside structs or classes which allows you to creates new objects. When you create an you can either pass it values or not. An example of would be:

let car = Vehicle() or let car = Vehicle(doors: 4, brand: "Ford")

the struct for the Vehicle class might look like:

class Vehicle {

 let doors: Int
 let brand: String

 init() {
     self.doors = 4
     self.brand = "Apple"
 } 

init(doors: int, brand: String) {
     self.doors = doors
     self.brand = brand
}

}

2 Answers

Your question is an interesting one. As you say, we know we have to write initializers for classes, and that structs come with a default member-wise initializer.

But the underlying question is why we'd ever want or need to write an initializer for a struct.

Say we want Student objects to have unique studentIDs, and we want them to know what their studentIDs are. Consider this code:

struct Student {
    var firstName: String
    var lastName: String
    var grade: Int
    var studentID: Int
    static var studentID = 0

    init(firstName: String, lastName: String, grade: Int) {
        self.firstName  = firstName
        self.lastName   = lastName
        self.grade      = grade
        Student.studentID++
        self.studentID = Student.studentID
    }
}

let s1 = Student(firstName: "Tom", lastName: "Jones", grade: 11)
s1.studentID //displays 1
let s2 = Student(firstName: "Nancy", lastName: "Drew", grade: 12)
s2.studentID //displays 2

There may be other ways of accomplishing this (e.g., perhaps with a didSet, etc.). But the above code does give a unique studentID to each new student object. And it uses a non-default initializer to do it.

P.S., The code works the same if you replace struct with class.

Hello :

Last night I was writing an answer for this question, but for some reason while updating my computer I lost track. But to add to the above answers, I will put my 2 cents.

Your question is very open to different answers, but I kind of have an idea where you want to go with this question.

Classes and Structs are like blueprints to create objects, which you can manipulate depending on the properties and methods that you give them. For example, think of a car as an object, this car has a lot of properties, but for the sake of the example we are only going to use a few.

A car has wheels, doors, and a color. Let's define a class that will create this object ( car ).

// This is a class that has properties but it does not have an initializer. 

class CarFactory {
  // Properties of a car

    var doors: Int?
    var wheels: Int?
    var color: String?
}

This CarFactory class has 3 properties (doors, wheels, colors). But it does not have an initializer. This means that we have a BluePrint, but we can NOT make the car if no initializer exist. Why? Because in order for this object to be fully prepared for use, the properties MUST have some values. Yes, we can also create an instance of CarFactory and initialize it's properties. Like this :

var honda = CarBluePrint()
honda.color = "Blue"
honda.doors = 2
honda.wheels = 4

// Now if you call any of this properties, it will return the values you gave them. 

But this process takes longer, and it's kind of annoying. So how can we make it easier and better? By giving it an initializer instead.

class CarFactory {
    // Properties of a car

    var doors: Int?
    var wheels: Int?
    var color: String?

    // Initializer
    init(doors: Int, wheels: Int, color: String){
        self.doors = doors
        self.wheels = wheels
        self.color = color
    }
}

So now that we have an initializer, we can create that object (car), this is called creating an instance.

// Creating an instance of CarFactory

var fordFiesta = CarFactory(doors: 4, wheels: 4, color: "Black")

fordFiesta.doors // Will return "4"
fordFiesta.wheels // Will return "4"
fordFiesta.color // Will return "Black"

With this initializer in place, then you can create more than just one instance of CarFactory, now you can create as many cars as you like.

I hope you understand why we need initializers, and when. If you have any more doubts, don't forge to ask.

Good luck and happy coding.