[swift-users] What is the intended response to Array change notification for dependents?
gardnermj at gmail.com
Tue Mar 7 13:04:23 CST 2017
> On Mar 7, 2017, at 10:14, Jens Alfke <jens at mooseyard.com> wrote:
>> On Mar 7, 2017, at 9:28 AM, Michael Gardner via swift-users <swift-users at swift.org> wrote:
>> The general approach would be to run a diff between your old and new arrays. Something like https://github.com/jflinter/Dwifft could help, though I haven't used it personally.
> I’ve implemented something like this in the past. It’s fairly expensive, though; that library does claim to use an optimized algorithm, but the cost is still a lot higher than just posting a notification. (And my own experience of using KVO is that notifications can become significant hot spots in performance, because they happen a lot.)
True, but if your array tends to change in limited ways (say, inserting/removing/changing a single contiguous slice), smart diffing algorithms are essentially linear-time. As long as equality-testing your items is fast and your source array isn't huge, diffing can work well. It's certainly simpler to integrate than the other approach, since it requires fewer changes to the rest of your code.
> On the other hand, if the array is expected to change often, more often than you want to redraw the GUI, it could make sense to ignore the fine-grained changes and just set a timer to trigger after a few hundred ms, which would then compare the old and new arrays this way and apply a minimal update to the view.
Good idea. Coalescing UI updates is a really useful technique in general.
>> Another approach is to build a wrapper around your source array with limited modification methods and a KVO-like notification system. The notifications can map cleanly to UITableView updates, and there's no extra diffing calculations involved. Of course, this method won't work if your source array needs to be modified by code you don't control.
> I would favor this, even though Swift’s strict typing [and lack of inheritance in struct types] means this class can’t interoperate with regular arrays. (Vs. Objective-C, where you can either subclass NSMutableArray, or even make an unrelated class that walks & quacks like an NSArray.)
> This seems likely to have been created by someone already; I wonder if there’s an implementation floating around Github?
I couldn't find one when I was working on a project that needed this a while ago, so I wrote my own. But it had some assumptions specific to that project, and I'm not sure how much work it would take to get it ready for general use. In any case I don't have time at the moment to do anything with it, unfortunately.
https://github.com/lorentey/GlueKit looks promising, though it's in alpha.
More information about the swift-users