[swift-evolution] [Pitch] Collection Type Element Property Observers

John McCall rjmccall at apple.com
Thu Mar 30 13:58:20 CDT 2017


> On Mar 30, 2017, at 2:37 PM, Sean Alling via swift-evolution <swift-evolution at swift.org> wrote:
> PROPOSAL:
> 
> I propose the addition of the following new property observers applicable to all Collection types (Dictionary, Set, and Array):
> 
> – willAdd(newValue) { … }
> – didAdd(newValue) { … }
> 
> – willRemove(oldValue) { … }
> – didRemove(oldValue) { … }
> 
> where, `newValue` and `oldValue` are immutable.
> 
> This would allow one to perform additional work or observer logic to values added and removed from collections.  This model is consistent with Swift syntax and may perhaps minimize the use of NSNotifications in some situations.
> 
> Currently, in order to perform this functionality some filtering and comparison logic would have to be performed from within a `willSet { … }` and `didSet { …}` call.  This change would not only ease that burden but promote a more visible and explicit expression that can further improve readability and traceability of functionality.

Figuring out that an arbitrary change to a collection is an "add" or a "remove" of a specific element is, well, let's just say it's complex.  If you're imagining that these observers would just get magically called when someone called the add or remove method on the property, that's not really how these language features work together.

The property behaviors proposal would let you do things like automatically computing differences and calling these observers, if you really want to do that.  But the better solution is almost certainly to (1) make the collection property private(set) and (2) just declare addToList and removeFromList methods that do whatever you would want to do in the observer.

John.

> 
> 
> EXAMPLE USAGE:
> 
> var list = [objects]() {
> 	willAdd(newValue) {
>> 	}
> 	didAdd(newValue) {
>> 	}
> }
> 
> var list = [key : object]() {
> 	willRemove(oldValue) {
>> 	}
> 	didRemove(oldValue) {
>> 	}
> }
> 
> 
> -----
> Sean Alling
> allings at icloud.com <mailto:allings at icloud.com>_______________________________________________
> swift-evolution mailing list
> swift-evolution at swift.org
> https://lists.swift.org/mailman/listinfo/swift-evolution

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-evolution/attachments/20170330/3eb68284/attachment.html>


More information about the swift-evolution mailing list