Skip to content
DeveloperMemos

Creating Factory Methods in Swift

Swift, Factory Method1 min read

A factory method is a creational design pattern that provides an interface for creating objects in a superclass but allows subclasses to alter the type of objects that will be created. It's useful when you want to separate object creation from the rest of your code, or when you need to create objects dynamically based on user input or other conditions.

To create a factory method in Swift, you'll need to define a static method in a class or struct that returns instances of itself or its subclasses. Let's see an example:

1class Vehicle {
2 let brand: String
3 let model: String
4
5 init(brand: String, model: String) {
6 self.brand = brand
7 self.model = model
8 }
9
10 static func createVehicle(brand: String, model: String) -> Vehicle {
11 return Vehicle(brand: brand, model: model)
12 }
13}
14
15class Car: Vehicle {
16 let seats: Int
17
18 init(brand: String, model: String, seats: Int) {
19 self.seats = seats
20 super.init(brand: brand, model: model)
21 }
22
23 override static func createVehicle(brand: String, model: String) -> Vehicle {
24 return Car(brand: brand, model: model, seats: 5)
25 }
26}

In this example, we have a Vehicle class with two properties and a createVehicle factory method that returns a Vehicle instance. We also have a Car subclass with an additional property and its own implementation of the createVehicle method that returns a Car instance with a default value for the seats property.

To create a Vehicle instance, you can simply call the createVehicle method on the Vehicle class:

1let vehicle = Vehicle.createVehicle(brand: "Toyota", model: "Corolla")

And to create a Car instance, you can call the same method on the Car class:

1let car = Car.createVehicle(brand: "BMW", model: "X5")

The createVehicle method is a factory method because it provides a way to create objects without exposing the object creation logic to the rest of the code.

You can use factory methods in many situations, such as when you need to create instances of different classes based on user input or configuration files, or when you want to provide a simpler interface for creating complex objects.

In Closing

Factory methods are a powerful tool for object-oriented programming, and Swift makes it easy to create them. By using factory methods, you can make your code more modular, extensible, and maintainable.