I'm defining a class structure that needs to notify its consumers when interesting things happen to it (gets new data, and so on). Similar to a delegate relationship, but there may be many consumers. And a more direct relationship than casting an NSNotification
into the wind.
My inclination in most Objective-C programs would just be to define a protocol, and let those consumers implement it and register themselves as id<MyProtocol>
; I'd stuff them into an NSMutableSet
, which I'd iterate over at opportune moments. My time spent writing C# would incline me to try to modify that approach somewhat to use generics in Swift (a la private var myConsumers = Set<MyProtocol>()
). That turns out to be a dark and painful rabbit hole, as far as I can tell. But rather than dive into it, let me back up and try to solve the real problem.
So: I have some class where instances will need to notify 0-N consumers of interesting things that happen. It'd be nice to allow those consumers to register and de-register themselves, since their lifespans may be shorter than my class.
What is the idiomatic Swift approach to implementing this pattern?