Any reason not use use a singleton “variable” in Swift?

后端 未结 3 1660
一个人的身影
一个人的身影 2020-11-29 09:58

For Sept 2015, here\'s exactly how you make a singleton in Swift:

public class Model
    {
    static let shared = Model()
    // ( for ocd friends ... privat         


        
3条回答
  •  醉酒成梦
    2020-11-29 10:27

    I can't see a single downside to this approach:

    • You can use different variables for different parts of the program (-> No namespace cramming if you don't like this I guess)
    • It's short, pretty, easy to use and makes sense when you read it. Model.shared.test() doesn't really make sense if you think about it, you just want to call test, why would I need to call shared when I just need a function.
    • It uses Swift's lazy global namespace: The class gets allocated and initialized when you use it the first time; if you never use it, it doesn't even get alloced/inited.

    In general, setting aside the exact idiom under discussion, regarding the use of singletons:

    • Recall that, of course, instead of using static var shared = Model() as a kind of macro to a singleton, as suggested in this Q, you can just define let model = Model() which simply creates a normal global (unrelated to singletons).
    • With Swift singletons, there has been discussion that arguably you want to add a private init() {} to your class, so that it only gets initialized once (noting that init could still be called in the same file).
    • Of course in general, when considering use of a singleton, if you don't really need a state and the class instance itself, you can simply use static functions/properties instead. It's a common mistake to use a singleton (for say "calculation-like" functions) where all that is needed is a static method.

提交回复
热议问题