0

I need to store an array of weak referenced protocols:

class Weak<T: AnyObject> {
    weak var value: T?
    init (_ value: T) {
        self.value = value
    }
}

protocol LocationSendingDelegate : AnyObject {
    func sendLocation(_ location: CLLocation)
}

private var locationSendingDelegates : [Weak<LocationSendingDelegate>] = [] // this line gives compiler error

The last line gives a compiler error:

'Weak' requires that 'any LocationSendingDelegate' be a class type

If I get rid of generics and declare:

class WeakLocationDelegate {
    weak var value: LocationSendingDelegate?
    init(_ value: LocationSendingDelegate) {
        self.value = value
    }
}

Then, this works fine:

private var locationSendingDelegates : [WeakLocationDelegate] = []

How can I do this with generics?

Someone else ran into this issue too but it wasn't resolved. This is not a duplicate. That question is about an array of weak classes whereas mine is about an array of weak protocols. Obviously the error I am getting about "class type" wouldn't happen if I were using class and not protocol.

3
  • 2
    protocols dont conform to themselves so you have to use existentials/any Commented Oct 13 at 1:53
  • Why not make the array itself weak? Wouldn't that prevent the element's ARC to be incremented by 1? That said, an array can hold 1 type. Therefore, you can do weak var locationSendingDelegates : [any LocationSendingDelegate] = [] instead. Is there something we're missing here? Commented Oct 13 at 3:46
  • When you have several receivers, better to use KVO or NotificationCenter. Commented Oct 13 at 7:26

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.