1

In Kotlin we can compose a Singleton object using

object MySingleton {
    // Some static variable.
}

without need to have a class and control its constructor to be private etc.

I try to search if there's equivalent Object in Swift language I can leverage, or I need to do my own Singleton class instance (e.g. private init() and static)?

Elye
  • 53,639
  • 54
  • 212
  • 474
  • 1
    “... or I need to do my own Singleton class instance (e.g. `private init()` and `static`)?” ... yep, that’s precisely how you do it. – Rob Aug 27 '20 at 05:24
  • For those who are looking for examples in Apple SDK - open Foundation module, at least, and look for constants starting from `public static var`, eg `struct CocoaError`. – Asperi Aug 27 '20 at 06:47

1 Answers1

0

It's a task of "make and forget" type. Just create the class and use it everywhere you need a singleton:

class Singleton {
    private static var uniqueInstance: Singleton?
    
    public static var instance: Singleton {
        if Singleton.uniqueInstance == nil {
            Singleton.uniqueInstance = self.init()
        }
        
        return Singleton.uniqueInstance!
    }

    required init() {}
}

class MyClass : Singleton {
    var param: Int = 0
}

let instanceOfMyClass: MyClass = MyClass.instance as! MyClass
print(instanceOfMyClass.param) // prints 0

instanceOfMyClass.param = 5

let anotherInstanceOfMyClass: MyClass = MyClass.instance as! MyClass
print(anotherInstanceOfMyClass.param) // prints 5
Roman Ryzhiy
  • 1,540
  • 8
  • 5