Created
December 8, 2017 16:00
-
-
Save oliverbarreto/e505308e3692da9f3ef4d974aab3d022 to your computer and use it in GitHub Desktop.
Singleton in Swift 4
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 1. --- The simple version... | |
class SingletonManager { | |
static let sharedInstance = SomeManager() | |
} | |
// The singleton object will then be accessible through the SingletonManager.sharedInstance() class method. | |
// 2. --- Or the more complex and secure version... | |
// [Full credit to](https://cocoacasts.com/what-is-a-singleton-and-how-to-create-one-in-swift/) | |
class NetworkManager { | |
// MARK: - Properties | |
private static var sharedNetworkManager: NetworkManager = { | |
let networkManager = NetworkManager(baseURL: API.baseURL) | |
// Configuration | |
// ... | |
return networkManager | |
}() | |
// MARK: - | |
let baseURL: URL | |
// Initialization | |
private init(baseURL: URL) { | |
self.baseURL = baseURL | |
} | |
// MARK: - Accessors | |
class func shared() -> NetworkManager { | |
return sharedNetworkManager | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment