In a protocol, I'd like to create a single instance from functions so I use a container to store the static instances like this:
protocol MyProtocol {
func networkService() -> NetworkService
}
extension MyProtocol {
func networkService() -> NetworkService {
if Singletons.networkService == nil {
Singletons.networkService = NetworkService(abc: 123)
}
return Singletons.networkService!
}
}
private enum Singletons {
static var networkService: NetworkService?
}
Later on, a type can conform to it and replace the default implementation, but also requires a single instance:
struct MyType: MyProtocol {
private static var networkService: NetworkService?
func networkService() -> NetworkService {
if Self.networkService == nil {
Self.networkService = NetworkService(abc: 555)
}
return Self.networkService!
}
}
What I'm hoping is to encapsulate this ceremony of creating the singleton by using a Property Wrapper, but on the type. I'd like to do something like this:
protocol MyProtocol {
func networkService() -> NetworkService
}
extension MyProtocol {
func networkService() -> NetworkService {
@Singleton
NetworkService(abc: 123)
}
}
////
struct MyType: MyProtocol {
func networkService() -> NetworkService {
@Singleton
NetworkService(abc: 555)
}
}
Is there a way to achieve this or something similar?