Chapter 4. Object Types

In the preceding chapter, I discussed some built-in object types. But I have not yet explained object types themselves. As I mentioned in Chapter 1, Swift object types come in three flavors: enum, struct, and class. What are the differences between them? And how would you create your own object type?

In this chapter, I’ll describe first object types generally and then each of the three flavors. Then I’ll explain three Swift ways of giving an object type greater flexibility: protocols, generics, and extensions. Finally, I’ll complete the survey of Swift’s main built-in types with three umbrella types and three collection types.

Object Type Declarations and Features

Object types are declared with the flavor of the object type (enum, struct, or class), the name of the object type (which should start with a capital letter), and curly braces:

class Manny {
struct Moe {
enum Jack {

The visibility of an object type to other code — its scope — depends upon where its declaration appears (compare “Variable Scope and Lifetime”):

Top level

Object types declared at the top level of a file will, by default, be visible to all files in the same module. This is the usual place for object type declarations.

Inside another type declaration

Sometimes it’s useful to declare a type inside the declaration of another type, giving it a namespace. This is called a nested type.

Function body

An object type declared within the body of a function will exist only inside ...

Get iOS 14 Programming Fundamentals with Swift now with O’Reilly online learning.

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