Vishal Chourasia Vishal Chourasia - 1 month ago 10
Swift Question

is it possible to deallocate a static variable manually in swift?

I need to store a static variable only one time when app is launched, and that to for short period of time.

i want to deallocate that static variable once it's use is over.

mz2 mz2
Answer

Yes, static variables can be declared with var and made optional with ?, just like instance and local variables.

class Y { }

class X {
    static weak var myOptionalStaticThing:Y? = Y()

    func foo() {
        // X.myOptionalStaticThing gets deallocated after this
        // if this were the only strong pointer to X.myOptionalStaticThing
        X.myOptionalStaticThing = nil
    }
}
Comments