Your first structure
Structures, or structs, are one of the named types in Swift that allow you to encapsulate related properties and behaviors. You can declare a new type, give it a name and then use it in your code.
In the example of the pizza business, you’ve been using x/y coordinate tuples to represent locations. As a first example of structures, promote locations from tuples to a structure type:
struct Location { let x: Int
let y: Int
}
This block of code demonstrates the basic syntax for defining a struct. In this case, the code declares a type named Location that combines both x and y coordinates.
The basic syntax begins with the struct keyword followed by the name of the type and a pair of curly braces. Everything between the curly braces is a member of the struct.
In this example, both members are properties. Properties are constants or variables that are declared as part of a type. Every instance of the type will have these properties. This means that in our example, every Location will have both an x and a y property.
You can instantiate a structure and store it in a constant or variable just like any other type you’ve worked with:
let storeLocation = Location(x: 2, y: 4)
To create the Location value, you use the name of the type along with a parameter list in parentheses. This parameter list provides a way to specify the values for the properties x and y. This is an example of a initializer. Initializers ensure that all of the properties are known before you start using them. This is one of the key safety features of Swift; accidentally using uninitialized variables is a big source of bugs in other languages. You didn’t need to declare this initializer in the Location type, Swift provides it automatically. You’ll learn a lot more about initializers in Chapter 13, “Methods”.
You may remember that there’s also a range involved, and now that the pizza business is expanding, there may be different ranges associated with different restaurants. You can create another struct to represent the delivery area of a restaurant, like so:
struct DeliveryArea { var range: Double let center: Location
}
var storeArea = DeliveryArea(range: 4, center: storeLocation)
Now there’s a new struct named DeliveryArea that contains a variable range property along with a constant center property. As you can see, you can have a struct value inside a struct value; here, you use the Location type as the type of the center property of the DeliveryArea struct.