'NSHashTable' requires that 'any MyCustomProtocolAnyObject' be a class type

130 views Asked by At

Curious, why I'm getting this error:

enter image description here

If I declare that only objects can conform to the protocol:

public protocol DayViewStateUpdating: AnyObject {
    func move(from oldDate: Date, to newDate: Date)
}

And then trying to instantiate an NSHashTableof that protocol:

private var clientsHashTable = NSHashTable<DayViewStateUpdating>.weakObjects()

I'm getting the error:

'NSHashTable' requires that 'any DayViewStateUpdating' be a class type

But the any DayViewStateUpdating is guaranteed to be a class type, as it's declared as AnyObject earlier. Or am I missing something?

Source code of the file in context: DayViewState

1

There are 1 answers

5
Alexander On BEST ANSWER

NSHashTable is expecting Objective-C style protocols, rather than Swift-style protocol existentials.

Marking your protocol as @objc protocol DayViewStateUpdating works.

But really, you can get away without needing NSHashTable here, by using a Weak wrapper like so:

public struct Weak<T: AnyObject> {
    weak var object: T?
    
    init(_ object: T) { self.object = object }
}

private var clientsHashTable = [Key: Weak<DayViewStateUpdating>]