2
class ShareData {
    class var sharedInstance: ShareData {
        struct Static {
            static var instance: ShareData?
            static var token: dispatch_once_t = 0
        }

        dispatch_once(&Static.token) {
            Static.instance = ShareData()
        }

        return Static.instance!
    }


    var someString : String! //Some String

    var selectedTheme : AnyObject! //Some Object

    var someBoolValue : Bool!

}

This is my singleton design.However , I want to know how I can clear all its data as and when required? Also can i have more than one singleton Class??

  • 1
    singleton design pattern means you can have only 1 instance of a specific class in your app – ddb Aug 25 '16 at 08:40
  • See http://stackoverflow.com/questions/24024549/using-a-dispatch-once-singleton-model-in-swift about the "modern" definition of a shared instance in Swift. – Martin R Aug 25 '16 at 08:43

2 Answers2

3

Since you've only got 3 properties on your singleton it would be far easier just to set up a method that nils each property in turn.

Once you start getting in to how to destroy and recreate your singleton, you get in to the realm of do you actually even want a singleton or should you just be using a regular object.

Nick Jones
  • 58
  • 6
3

You are creating a Singleton with the syntax available in... 2014

Today there's a better syntax to define a Singleton class

final class SharedData {

    static let sharedInstance = SharedData()
    private init() { }
    var someString: String?
    var selectedTheme: AnyObject?
    var someBoolValue: Bool?

    func clear() {
        someString = nil
        selectedTheme = nil
        someBoolValue = nil
    }
}

As you can see I also added the clearData() method you were looking for.

Luca Angeletti
  • 58,465
  • 13
  • 121
  • 148
  • Though I up-voted your solution it would be nice if you have a var of the instance as an attribute then just set that to nil instead of setting every variable in the class to nil. like https://stackoverflow.com/a/28398928/4693042 – GyroCocoa Nov 03 '17 at 11:32