Kamil Harasimowicz
Kamil Harasimowicz

Reputation: 4994

Swift: `weak` reference in tuple

Is it possible to create in Swift 4 tuple with weak reference?

Something like this:

let x: (name: weak MyClass, name2: weak MyClass2)

Upvotes: 2

Views: 966

Answers (1)

Luca Angeletti
Luca Angeletti

Reputation: 59526

First of all a weak var must be Optional. Secondly, as @Hamish said in the comments, you cannot define a tuple field as weak.

Workaround

However, if you really want to use tuples, here's a workaround

Step 1 Let's define a wrapper with a weak reference to it's internal object

struct WeakWrapper<Element:AnyObject> {
    weak var value:Element?

    init(_ value:Element) {
        self.value = value
    }
}

Step 2 Your 2 classes

class MyClass1 {
    deinit {
        debugPrint("Deinit MyClass1")
    }
}
class MyClass2 {
    deinit {
        debugPrint("Deinit MyClass1")
    }
}

Step 3 This is how we define the tuple

let x: (name0: WeakWrapper<MyClass1>, name1: WeakWrapper<MyClass2>)

Step 4 And this is how we populate it

x = (name0: WeakWrapper(MyClass1()), name1:WeakWrapper(MyClass2()))

Step 5 The objects objects of type MyClass1 and MyClass2 we created will be deallocated on the next line because there is no strong reference to them

"Deinit MyClass1"
"Deinit MyClass1"

Upvotes: 6

Related Questions