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 asInt
.isGood
typed asBool
.
Instructions
Create a structure named Book
without any properties.
Inside of Book
, add the properties:
title
with typeString
.pages
with typeInt
.