Learn
Classes
Creating an Instance

To refresh, a class is simply a template to create objects. The term “object” is often used to refer to an instance of a class. So for example, a building blueprint is a class and each house is an object, or an instance of the class.

In the previous example, we created a class to model students:

class Student { var name = "" var year = 0 var gpa = 0.0 var honors = false }

With this blueprint, we can now start creating instances of Student. We can make hundreds or even thousands of them if we want to! Let’s make an instance of Student to model the infamous Ferris Bueller.

The syntax for creating an instance:

var ferris = Student()

Here, we’ve created a single instance of Student and saved it to ferris. We can now access and edit the property values by using the dot syntax, .property.

ferris.name = "Ferris Bueller" ferris.year = 12 ferris.gpa = 3.81 ferris.honors = false

And now we know how to get Ferris Bueller out of a class. 💨

Instructions

1.

Given the Restaurant class, we now want to use it to model a restaurant called Bob’s Burgers.

Created an instance of it and name the variable bobsBurgers.

2.

Modify bobsBurgers‘s properties so that:

  • .name is "Bob's Burgers"
  • .type is ["Burgers", "Fast Food"]
  • .rating is 3.5
  • .delivery is true
3.

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

Folder Icon

Take this course for free

Already have an account?