Chapters

Hide chapters

Design Patterns by Tutorials

Third Edition · iOS 13 · Swift 5 · Xcode 11

20. Composite Pattern
Written by Jay Strawn

Heads up... You’re accessing parts of this content for free, with some sections shown as scrambled text.

Heads up... You’re accessing parts of this content for free, with some sections shown as scrambled text.

Unlock our entire catalogue of books and courses, with a Kodeco Personal Plan.

Unlock now

The composite pattern is a structural pattern that groups a set of objects into a tree structure so they may be manipulated as though they were one object. It uses three types:

  1. The component protocol ensures all constructs in the tree can be treated the same way.
  2. A leaf is a component of the tree that does not have child elements.
  3. A composite is a container that can hold leaf objects and composites.

Both composites and leaf nodes derive from the component protocol. You can even have several different leaf classes held in a composite object.

For example, an Array is a composite. The component is the Array itself. The composite is a private container used by Array to contain leaf objects. Each leaf is a concrete type such as Int, String or whatever you add to the Array.

When should you use it?

If your app’s class hierarchy forms a branching pattern, trying to create two types of classes for branches and nodes can make it difficult for those classes to communicate.

You can solve this problem with the composite pattern by treating branches and nodes the same by making them conform to a protocol. This adds a layer of abstraction to your models and ultimately reduces their complexity.

Playground example

Open AdvancedDesignPatterns.xcworkspace in the Starter directory, and then open the Composite page.

What should you be careful about?

Make sure your app has a branching structure before using the composite pattern. If you see that your objects have a lot of nearly identical code, conforming them to a protocol is a great idea, but not all situations involving protocols will require a composite object.

Tutorial project

Throughout this section, you’ll add functionality to an app called Defeat Your ToDo List.

Key points

You learned about the composite pattern in this chapter. Here are its key points:

Have a technical question? Want to report a bug? You can ask questions and report bugs to the book authors in our official book forum here.
© 2026 Kodeco Inc.

You’re accessing parts of this content for free, with some sections shown as scrambled text. Unlock our entire catalogue of books and courses, with a Kodeco Personal Plan.

Unlock now