Implementing the strategy pattern

In this section, the strategy pattern will be demonstrated by showing how compression strategies can be swapped out at runtime. Let's begin this example by creating a CompressionStrategy protocol that each one of the compression types will conform to.

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

This protocol defines one method named compressFiles() that accepts a single parameter, which is an array of strings that contain the paths to the files to compress. Now let's create two structures that conform to the CompressionStrategy protocol named ZipCompressionStrategy and the RarCompressionStrategy:

struct ZipCompressionStrategy: CompressionStrategy { func compressFiles(filePaths: ...

Get Swift 4 Protocol-Oriented Programming - Third Edition now with O’Reilly online learning.

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