在协议中,我想从函数创建单个实例,因此我使用容器来存储静态实例,如下所示:
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?
}
稍后,一个类型可以符合它并替换默认实现,但也需要一个实例:
struct MyType: MyProtocol {
private static var networkService: NetworkService?
func networkService() -> NetworkService {
if Self.networkService == nil {
Self.networkService = NetworkService(abc: 555)
}
return Self.networkService!
}
}
我希望通过使用属性包装器来封装这个创建单例的仪式,但是在类型上。我想做这样的事情:
protocol MyProtocol {
func networkService() -> NetworkService
}
extension MyProtocol {
func networkService() -> NetworkService {
@Singleton
NetworkService(abc: 123)
}
}
////
struct MyType: MyProtocol {
func networkService() -> NetworkService {
@Singleton
NetworkService(abc: 555)
}
}
有没有办法实现这个或类似的东西?