Help with understanding the use of init()

I’m not really understanding the use of, or point of having an init() method here? The output of the following code is the same with or without the init() method.
I understand it initialises a structure, but doesn’t line 2 and 3 do the exact same thing? I also don’ understand why we assign title to self.title on line 6. Can anyone shed some light on this? Thanks.

struct Book {
var title: String
var pages: Int

init (title : String, pages : Int) {
self.title = title
self.pages = pages
}
}

var theHobbit = Book(title : “The Hobbit”, pages : 300)

print(theHobbit)

This is because of something called a memberwise initializer that is only available to Swift’s Structure constructs.

Basically, Swift will automatically make an init() method for you that includes the struct’s defined properties if you don’t add an init() method of your own.

For more information on this, you can check out the official documentation, or one of the articles linked at the bottom of this reply.

However, I would highly encourage you to not rely on memberwise initializer until you really understand traditional init() methods. For one, Swift’s classes don’t have memberwise initializers, so you will need to know how to write them anyway for Class constructs. Second, memberwise initializers do have limitations that a traditional init() does not. And finally, most other object-oriented programming languages require the init() method for classes and objects, so learning how to write them is a useful and transferable skill.

In a traditional init() method, the line

self.title = title

will set the object or construct’s title property (e.g., Book.title) to the value of whatever was passed in for the object’s title parameter.


1 Like