Can Swift protocols be singleton?

假如想象 提交于 2019-12-02 02:21:49

问题


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


回答1:


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.



来源:https://stackoverflow.com/questions/35757054/can-swift-protocols-be-singleton

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!