--- url: "https://refactoring.guru/design-patterns/strategy/swift/example" titulek: "Strategy in Swift / Design Patterns" h1: "Strategy in Swift" popis: "Strategy pattern in Swift. Full code example in Swift with detailed comments and explanation. Strategy is a behavioral design pattern that turns a set of behaviors into objects and makes them interchangeable inside original context object." jazyk: "en" kanonicka: "https://refactoring.guru/design-patterns/strategy/swift/example" drobecky: ["Home", "Design Patterns", "Strategy", "Swift"] zdroj: "live" wayback_snapshot: "" stazeno: "2026-09-13 22:22:59" znaku: 6751 slov: 937 kodovani: "utf-8" sha256: "83fa89d726acef9fdf6a3c9976d0f105c01b2e0ef903af6230642ff771a0767d" --- # **Strategy** in Swift **Strategy** is a behavioral design pattern that turns a set of behaviors into objects and makes them interchangeable inside original context object. The original object, called context, holds a reference to a strategy object. The context delegates executing the behavior to the linked strategy object. In order to change the way the context performs its work, other objects may replace the currently linked strategy object with another one. [Learn more about Strategy](/design-patterns/strategy) **Complexity:** **Popularity:** **Usage examples:** The Strategy pattern is very common in Swift code. It’s often used in various frameworks to provide users a way to change the behavior of a class without extending it. **Identification:** Strategy pattern can be recognized by a method that lets a nested object do the actual work, as well as a setter that allows replacing that object with a different one. The following examples are available on [Swift Playgrounds](https://www.alemohamad.com/playgrounds) . Kudos to [Alejandro Mohamad](https://www.alemohamad.com) for creating the Playground version. ## Conceptual Example This example illustrates the structure of the **Strategy** design pattern and focuses on the following questions: - What classes does it consist of? - What roles do these classes play? - In what way the elements of the pattern are related? After learning about the pattern’s structure it’ll be easier for you to grasp the following example, based on a real-world Swift use case. #### **Example.swift:** Conceptual example ``` import XCTest /// The Context defines the interface of interest to clients. class Context { /// The Context maintains a reference to one of the Strategy objects. The /// Context does not know the concrete class of a strategy. It should work /// with all strategies via the Strategy interface. private var strategy: Strategy /// Usually, the Context accepts a strategy through the constructor, but /// also provides a setter to change it at runtime. init(strategy: Strategy) { self.strategy = strategy } /// Usually, the Context allows replacing a Strategy object at runtime. func update(strategy: Strategy) { self.strategy = strategy } /// The Context delegates some work to the Strategy object instead of /// implementing multiple versions of the algorithm on its own. func doSomeBusinessLogic() { print("Context: Sorting data using the strategy (not sure how it'll do it)\n") let result = strategy.doAlgorithm(["a", "b", "c", "d", "e"]) print(result.joined(separator: ",")) } } /// The Strategy interface declares operations common to all supported versions /// of some algorithm. /// /// The Context uses this interface to call the algorithm defined by Concrete /// Strategies. protocol Strategy { func doAlgorithm(_ data: [T]) -> [T] } /// Concrete Strategies implement the algorithm while following the base /// Strategy interface. The interface makes them interchangeable in the Context. class ConcreteStrategyA: Strategy { func doAlgorithm(_ data: [T]) -> [T] { return data.sorted() } } class ConcreteStrategyB: Strategy { func doAlgorithm(_ data: [T]) -> [T] { return data.sorted(by: >) } } /// Let's see how it all works together. class StrategyConceptual: XCTestCase { func test() { /// The client code picks a concrete strategy and passes it to the /// context. The client should be aware of the differences between /// strategies in order to make the right choice. let context = Context(strategy: ConcreteStrategyA()) print("Client: Strategy is set to normal sorting.\n") context.doSomeBusinessLogic() print("\nClient: Strategy is set to reverse sorting.\n") context.update(strategy: ConcreteStrategyB()) context.doSomeBusinessLogic() } } ``` #### **Output.txt:** Execution result ``` Client: Strategy is set to normal sorting. Context: Sorting data using the strategy (not sure how it'll do it) a,b,c,d,e Client: Strategy is set to reverse sorting. Context: Sorting data using the strategy (not sure how it'll do it) e,d,c,b,a ``` ## Real World Example #### **Example.swift:** Real world example ``` import XCTest class StrategyRealWorld: XCTestCase { /// This example shows a simple implementation of a list controller that is /// able to display models from different data sources: /// /// (MemoryStorage, CoreDataStorage, RealmStorage) func test() { let controller = ListController() let memoryStorage = MemoryStorage() memoryStorage.add(usersFromNetwork()) clientCode(use: controller, with: memoryStorage) clientCode(use: controller, with: CoreDataStorage()) clientCode(use: controller, with: RealmStorage()) } func clientCode(use controller: ListController, with dataSource: DataSource) { controller.update(dataSource: dataSource) controller.displayModels() } private func usersFromNetwork() -> [User] { let firstUser = User(id: 1, username: "username1") let secondUser = User(id: 2, username: "username2") return [firstUser, secondUser] } } class ListController { private var dataSource: DataSource? func update(dataSource: DataSource) { /// ... resest current states ... self.dataSource = dataSource } func displayModels() { guard let dataSource = dataSource else { return } let models = dataSource.loadModels() as [User] /// Bind models to cells of a list view... print("\nListController: Displaying models...") models.forEach({ print($0) }) } } protocol DataSource { func loadModels() -> [T] } class MemoryStorage: DataSource { private lazy var items = [Model]() func add(_ items: [Model]) { self.items.append(contentsOf: items) } func loadModels() -> [T] { guard T.self == User.self else { return [] } return items as! [T] } } class CoreDataStorage: DataSource { func loadModels() -> [T] { guard T.self == User.self else { return [] } let firstUser = User(id: 3, username: "username3") let secondUser = User(id: 4, username: "username4") return [firstUser, secondUser] as! [T] } } class RealmStorage: DataSource { func loadModels() -> [T] { guard T.self == User.self else { return [] } let firstUser = User(id: 5, username: "username5") let secondUser = User(id: 6, username: "username6") return [firstUser, secondUser] as! [T] } } protocol DomainModel { var id: Int { get } } struct User: DomainModel { var id: Int var username: String } ``` #### **Output.txt:** Execution result ``` ListController: Displaying models... User(id: 1, username: "username1") User(id: 2, username: "username2") ListController: Displaying models... User(id: 3, username: "username3") User(id: 4, username: "username4") ListController: Displaying models... User(id: 5, username: "username5") User(id: 6, username: "username6") ``` ## **Strategy** in Other Languages