2

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)?

2
  • 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. Commented Aug 27, 2020 at 5: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. Commented Aug 27, 2020 at 6:47

1 Answer 1

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
Sign up to request clarification or add additional context in comments.

2 Comments

This approach is unnecessarily overcomplicated. See the linked duplicate for a much clearer solution.
@DávidPásztor This "unnecessarily overcomplicated" approach can be inherited. You cannot say this about the "much clearer solution".

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.