Learn

With structures, we can create our own data type and use them to model everyday objects with their own unique characteristics. Here’s the basic syntax for a structure:

struct Name {
  Properties
}

The struct keyword followed by the name of the structure creates the structure. By convention, this name is capitalized. Then inside the curly braces that follow is the body and where properties and methods (which we’ll explore in a later exercise) unique to the structure are defined.

Here’s an example of a struct that models a dog:

struct Dog { var age: Int var isGood: Bool }

Structures tend to have singular names, hence Dog instead of Dogs. When we look closer at the Dog structure, we see it has two properties which look like typed variables:

  • age typed as Int.
  • isGood typed as Bool.

Instructions

1.

Create a structure named Book without any properties.

2.

Inside of Book, add the properties:

  • title with type String.
  • pages with type Int.

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?