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 strategy pattern

In this section, we will demonstrate the strategy pattern by showing you how we could swap out compression algorithms at runtime. Let's begin this example by creating a CompressionStrategy protocol that each one of the compression types will conform to. Let's look at the following code:

protocol CompressionStrategy { 
  func compressFiles(filePaths: [String]) 
} 

This protocol defines a method named compressFiles() that accepts a single parameter, which is an array of strings that contain the paths to the files we want to compress. We will now create two structures that conform to this protocol. These are the ZipCompressionStrategy and the RarCompressionStrategy structures, which are as follows:

struct ZipCompressionStrategy: ...

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