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 Object-Oriented Swift Value vs Reference Types Structs vs Classes

Srinivasan Senthil
Srinivasan Senthil
2,266 Points

Struct VS Classes ?

Could some one explain me the following. Why is it that an initializer required when i create a Class, but thats not the case when i create a struct.

My Code:

// I dont need to create a initializer here.
struct structContact
{
    var Firstname : String
    var Lastname  : String
}

var Student1 = structContact(Firstname: "James", Lastname: "Peter")
Student1.Firstname
Student1.Lastname
// // I do need to create a initializer here.
class classContact 
{
    var firstname : String
    var lastname  : String

    init(firstname : String, lastname : String)
    {
    self.firstname = firstname
    self.lastname  = lastname
    }

}
var student2 = structContact(Firstname: "Curious", Lastname: "George")
student2.Firstname
student2.Lastname

If your answer is something related to synthesized initializer, please let me know what it is.

Kindly explain in detail. Thanks.

1 Answer

Roy Hochstenbach
Roy Hochstenbach
3,226 Points

The idea of a class is that it gets loaded into memory, and then you can communicate with it afterwards. You don't have to give it any parameters, as you can do that later on. So for example, you could also do it like this:

var student = classContact;

student.Firstname = "Curious;

student.Lastname = "George";

Basically the init method is the default method that is executed when loading the class.

I think this is wrong, both will require parameters unless a default or nil is assigned.