8 Structures and Classes

WHAT YOU WILL LEARN IN THIS CHAPTER:                              

  • How to define a structure
  • How to create an instance of a structure
  • How to initialize a structure’s properties
  • How to compare two structures
  • How to define a class
  • How to define properties within a class
  • The different types of properties
  • How to create initializers for a class
  • How to compare instances of a class
  • How to define methods in a class

Object-oriented programming (OOP) is one of the most important features in Swift programming—and structures and classes play an important role in supporting that. In Swift, structures and classes share many similarities, and many concepts that apply to classes apply to structure as well.

In this chapter, you will learn how to define structures and classes, and then use them. You will learn how to define the different types of properties in structures and classes, as well as define methods. By the end of this chapter, you will have a solid understanding of how structures and classes work in Swift.

STRUCTURES

A structure is a special kind of data type that groups a list of variables and places them under a unified name. The group of variables contained within a structure may have diverse data types. Structures are useful for storing related group of data. For example, consider a scenario in which you are implementing a game of Go. Figure 8-1 shows the board layout of Go. A typical game of Go has a grid of 19 × 19 lines, and players place markers, ...

Get Beginning Swift Programming 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.