0

Is this a possible way to make shorter singletons without shared instance? Why people are creating a shared instance var instead of using this way?

Simple:

class Singleton {

    static var someVar = "Cool it works!"

    class func execute() {
        print(someVar)
    }

Singleton.execute()

Singleton.someVar = "var changed"
Singleton.execute()

// console:
// Cool it works!
// var changed

Handlers:

class Singleton {

    static var someVar = "Some Var passed to the handler"

    class func execute(handler:(String)->String) {
        let varReturnedFromHandler = handler(someVar)
        print(varReturnedFromHandler)
    }
}
Singleton.execute { (varFromFunction:String) in

    print(varFromFunction)
    return "Returned var from handler"
}
// console:
// Some Var passed to the handler
// Returned var from handler
Paulo Bruckmann
  • 331
  • 4
  • 7
  • 2
    That's not a singleton. It's just a class that only has class variables and class functions. – DarkDust Apr 20 '16 at 13:50
  • 1
    So this question is _almost_ a duplicate of [Difference between static class and singleton pattern](http://stackoverflow.com/questions/519520/difference-between-static-class-and-singleton-pattern?rq=1). – DarkDust Apr 20 '16 at 13:52
  • This is not really a swift question more of a design pattern question. Just stay away from singletons in general. Write regular classes and if you want a globally scoped one in your app instantiate it there and pass it around. Just create 1 instance. – GregP Apr 20 '16 at 14:12

0 Answers0