Skip to content

Instantly share code, notes, and snippets.

@oliverbarreto
Created December 8, 2017 16:00
Show Gist options
  • Save oliverbarreto/e505308e3692da9f3ef4d974aab3d022 to your computer and use it in GitHub Desktop.
Save oliverbarreto/e505308e3692da9f3ef4d974aab3d022 to your computer and use it in GitHub Desktop.
Singleton in Swift 4
// 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