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 the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.