Dennis Dennis - 6 months ago 170
Swift Question

How to destory a singleton in swift

How to destroy a singleton in swift



I create a singleton like this:

class MyManager {
private static let sharedInstance = MyManager()
class var sharedManager : MyManager {
return sharedInstance
}
}

Answer

Just a simple example on how to dispose the current instance of a Singleton:

import UIKit

class AnyTestClass
{
    struct Static
    {
        private static var instance: AnyTestClass?
    }

    class var sharedInstance: AnyTestClass
    {
        if Static.instance == nil
        {
            Static.instance = AnyTestClass()
        }

        return Static.instance!
    }

    func dispose()
    {
        AnyTestClass.Static.instance = nil
        print("Disposed Singleton instance")
    }

    func saySomething()
    {
        print("Hi")
    }

}

// basic usage
AnyTestClass.sharedInstance.saySomething()
AnyTestClass.sharedInstance.dispose()

Hope it might help.