Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can Swift protocols be singleton?

I have tried using the single line singleton initialization(as in a class) for a singleton, here are some error screenshots: enter image description here

enter image description here

Can you help me understand these errors, and also, if a singleton protocol is even possible or not? Thanks in advance

like image 331
Nikita P Avatar asked Dec 08 '22 23:12

Nikita P


1 Answers

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.

like image 191
Rob Napier Avatar answered Dec 22 '22 00:12

Rob Napier