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 the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.