SoFunction
Updated on 2025-04-10

Example of method that defines singletons in Swift

What is a single case

Singleton pattern is the simplest one in design patterns. Some pattern masters do not even call it a pattern, but an implementation technique, because design patterns focus on abstraction of the relationship between objects, while singleton pattern only has one object.

Singleton Pattern, also known as singleton pattern, is a commonly used software design pattern. When applying this pattern, the class of a singleton object must ensure that only one instance exists.

The single instance Singleton design pattern may be the most widely discussed and used design pattern, and it may also be the most asked design pattern in the interview. The main purpose of this design pattern is to only have one class instance in the entire system. Of course, it is inevitable to do this, such as the global configuration information of your software, or a Factory, or a main control class, etc.

How to create a singleton in swift

There are two ways to create singletons in swift

The way of global variables

let sharedNetworkManager = NetworkManager(baseURL: )
class NetworkManager {
 // MARK: - Properties
 let baseURL: URL
 // Initialization
 init(baseURL: URL) {
  = baseURL
 }
}

Use this global variable for reference

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
 print(sharedNetworkManager)
 return true
}

Static properties and privatization construction methods

class NetworkManager {
 // MARK: - Properties
 private static var sharedNetworkManager: NetworkManager = {
 let networkManager = NetworkManager(baseURL: )
 // Configuration
 // ...
 return networkManager
 }()
 // MARK: -
 let baseURL: URL
 // Initialization
 private init(baseURL: URL) {
  = baseURL
 }
 // MARK: - Accessors
 class func shared() -> NetworkManager {
 return sharedNetworkManager
 }
}

Directly call class methods for reference

()

Summarize

The above is the entire content of this article. I hope that the content of this article has a certain reference value for everyone's study or work. If you have any questions, you can leave a message to communicate. Thank you for your support.

Reference from:What Is a Singleton and How To Create One In Swift