Learn
Classes
The Init Method

In the previous exercise, we’ve supplied our instances’ properties with default values. However, if we know that our class 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:

class className {
  var property = value
  init (property: valueType) {
     self.property = property
  }
}

The init() method is special since it doesn’t require the func keyword and gets called upon instance creation. Another unique feature is that the init() method uses the self keyword to reference itself.

Let’s see the init() in action:

class Student { var name = "" var year = 0 var gpa = 0.0 var honors = false init(name: String, year: Int, gpa: Double, honors: Bool) { self.name = name self.year = year self.gpa = gpa self.honors = honors } }

So now we can create an instance of the Student class and initialize its properties in one line:

var bart = Student(name: "Bart Simpson", year: 4, gpa: 0.0, honors: false)

Note that all properties must have arguments and the ordering of the params must match the ordering of the declared properties.

Instructions

1.

In the Restaurant class, create an init() method that has four parameters:

  • name that is type String
  • type that is type [String]
  • rating that is type Double
  • delivery that is type Bool

Inside the method, use the self keyword to assign each property its corresponding parameter.

2.

Outside of the class, create an instance of a Restaurant named laRatatouille with the following values for its properties:

  • name: "La Ratatouille"
  • type: ["French"]
  • rating: 4.7
  • delivery: false

Make sure to do this in one line!

3.

Let’s print out all four properties of laRatatouille one by one using print().

Folder Icon

Take this course for free

Already have an account?