Chapter 6. Structures, Properties, and Methods: Custom Types and Beyond

image

Working with data often involves defining your own kinds of data. Structures—often shortened to their Swift language keyword, structs—allow you to create your own custom data types (just like String and Int are data types) by combining other types. Using structs to represent the data that your Swift code is working with allows you to step back and consider how the data that flows through your code fits together. Structs can hold variables and constants (which are called properties when they’re inside a struct) and functions (which are called methods). Let’s add some structure to your world, and dive into structs.

image

You can make your own types in Swift.

Note

Like String, Int, etc.

The most common way of doing this is with a feature called structures, or structs for short. This might be surprising if you’ve used another language, where people can be stuck in their classy ways.

Structs give you the phenomenal power to contain variables, constants, and functions within a type of your own choosing!

This is a Pizza type, defined as a struct:

image

After defining your Pizza struct, you can then create an instance ...

Get Head First Swift now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.