I have tried using the single line singleton initialization(as in a class) for a singleton, here are some error screenshots:
Can you help me understand these errors, and also, if a singleton protocol is even possible or not? Thanks in advance
A protocol itself can't be a singleton. That wouldn't make any sense. A protocol is something that other types conform to.
But if you wanted to declare that things that conform to Singleton
follow some rule, such as offering a sharedInstance
, then that's fine. Your syntax is just incorrect. You need to use a var
with get
rather than let
.
protocol Singleton {
static var sharedInstance: Self { get }
}
In principle, you could automatically create this instance by providing a default implementation, but Swift doesn't allow you to create storage in an extension. While it would be possible to pull this off with some kind of global cache, it's hard to imagine it being worth the trouble.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With