Assigning a singleton to a variable (Swift)

100 views Asked by At

Is it an anti-pattern to have the following code?

I want to have the singleton (ClassB) as a variable so that I have some sort of dependency injection while still using a singleton. But I have been hinted that without having mySingleton as weak I could have memory leaks. But I cannot think of any such scenario...

class ClassA {
    var mySingleton: ClassB? = ClassB.shared

    deinit {
        print("deinit A")
    }
}

class ClassB {
static let shared = ClassB()

    deinit {
        print("deinit B")
    }
 }

var a1: ClassA? = ClassA()
var b1: ClassB? = ClassB()

a1?.mySingleton = b1

a1 = nil
b1 = nil

EDIT: made improvements to the code although they irrelevant to the question which is if it is an anti-pattern to assign a singleton to a variable and specifically it if can cause memory leaks

0

There are 0 answers