Learn
Structures
New Type

In the previous exercises, we’ve done a lot with structures: we’ve created a structure, made instances, and added properties and methods, etc. So just take a second to pause and consider our achievement — we modeled a real-life object in our code! In doing so, we also made a new data type in our program!

Let’s take a quick look back at our example:

struct Dog { var age = 0 var isGood = true } var eloise = Dog()

We can use Swift’s built-in function type(of:) function and check what is eloise‘s type:

type(of: eloise) // Dog

That’s right, eloise is a Dog type. Remember, we can also set an explicit type for our variables. Let’s say we have another dog named bucket:

var bucket: Dog = Dog()

Notice that we can specify bucket‘s type as Dog. This means we can also use structures inside other structures as property values:

struct Pets { var petDog: Dog var petCat: Cat }

Above, we created another structure Pets that helps us keep track of our pets. For the petDog property, we typed it as Dog. We also added another property petCat for when we make a Cat structure. With the ability to create new types, it opens the door for us to model more complex real-life objects!

Instructions

1.

Let’s see type() in use in our own code.

Use a print() statement to print out the value of type(of: journey).

2.

Create another variable bts explicitly typed as Band and assign to it an instance of Band with the properties:

  • genre with the value "kpop".
  • members with the value 7.
  • isActive with the value true.
Folder Icon

Take this course for free

Already have an account?