O'Reilly logo

Mastering Swift 4 - Fourth Edition by Jon Hoffman

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Implementing the command pattern

In this section, we will demonstrate how to use the command pattern by creating a Light type. In this type, we will define the lightOnCommand and lightOffCommand commands and will use the turnOnLight() and turnOffLight() methods to invoke these commands. We will begin by creating a protocol named Command, which all of the command types will conform to. Here is the command protocol:

protocol Command { 
  func execute() 
}

This protocol contains a method named execute(), which will be used to execute the command. Now, let's look at the command types that the Light type will use to turn the light on and off. They are as follows:

 

struct RockerSwitchLightOnCommand: Command { func execute() { print("Rocker Switch:Turning ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required