Learn

Now that we know how to create a structure we should also know how to create customized instances of that structure. But, what if we’re creating a lot of instances, do we really need to customize every single instance? In some cases, we might find that that instance’s properties don’t always need a unique value and that we can reuse some common values.

We’ll use Swift’s concept of default property values to set values for properties inside our structures. This will save us time later on once we get to creating instances.

struct Dog { var age = 0 var isGood = true }

Notice that the syntax for assigning default values is identical to assigning values to variables. Later, when we create an instance of Dog, that instance’s age value will automatically be 0 and isGood‘s value true. This concept might save us time later on since all dogs are good (🐶), and they’re 0 years old right after birth.

As another example, let’s look back at our introductory structures GIF, we’ll see that our building blueprint has default property values: two floors and a triangular roof. As we created new building instances, we kept some values and changed others.

Instructions

1.

In the provided Book struct, give the following default values for:

  • title to be "".
  • pages to be 0.

Take this course for free

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