In the previous exercise, we’ve supplied our instances’ properties with default values. However, if we know that our struct instances vary a lot from one to another, we can include an init() method for customization. The following syntax is used for an init() method:

struct SampleStruct {
  var structProperty: Type
  init (structProperty: Type) {
     self.structProperty = structProperty

Since methods are essentially functions specific to a type (in this case, the type is a structure), the syntax looks a lot like functions. The init() method is special since it doesn’t require the func keyword and gets called upon instance creation. Like functions, methods can have parameters but don’t need to have any. Another unique feature is that the init() method uses the self keyword to reference itself. Let’s see init() in action:

struct Dog { var age : Int var isGood : Bool init (age: Int, isGood: Bool) { self.age = age self.isGood = isGood } } // Using the init() method: var bucket = Dog(age: 4, isGood: true) print(bucket.age) // Prints: 4 print(bucket.isGood) // Prints: true

In Dog‘s init() method, we set parameters for Dog‘s properties. Inside the method, we assign self.age and self.isGood their respective values. When we create bucket, an instance of Dog, we have to pass into the parentheses the arguments needed to assign values to bucket‘s properties. From our print() statements we’ve confirmed that bucket‘s properties were assigned correctly.



In the Book struct, create an init() method that has two parameters:

  • title that is type String.
  • pages that is type Int.

Create an instance of a Book named theHobbit with the values title: "The Hobbit" and pages: 300.

Take this course for free

Mini Info Outline Icon
By signing up for Codecademy, you agree to Codecademy's Terms of Service & Privacy Policy.

Or sign up using:

Already have an account?