Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

iOS Swift Enums and Structs Structs and their Methods Initializers

Can you help me explain "self" and init() method again?

I didn't quite get it. What is the need for "self" and init() method? All I can understand is that it has something to do with initializing the variable beforehand. So you don't have to do it afterwards? Maybe?

And if you can again explain me the two things separately without not having relationship to each other.. Also whenever you write init() method do we always need to write the var. as "self" in it?

1 Answer

Sam Chaudry
Sam Chaudry
25,519 Points

Ok so Self is used to refer to an instance variable of that class, so for example you might have a label called name and you want to set it's text value to "Raj" within a class called Person. So your code would be

//Example label self.nameLabel.text = "Raj";

So here I am taking a variable called 'nameLabel' which belongs to the 'Person' class and setting it's text property to "Raj"

init on the other hand is short for initialiser this is the process of getting an object ready for use, this process may include setting properties of that class to a specific value.

//Class called person

class Person {

//Name property var name:String;

// initialising class with users name init(user:String){

   //Here we set the Person class name property to the user name. So when this object is ready for use the name will be        set to the users input
    self.name = user;


} //So we initialise the object with a string and set it the name property
var users = Person(user: "Raj");

//Then when we then access the name property it prints Raj to the console as it has been initialised with a user. var currentUser = users.name;