2022-03-27

PreferenceKey Quirks

PreferenceKey has a few quirks that have tripped me up. One is the reduce(value:nextValue:) implementation. The other is that a PreferenceKey will not propagate upward past a View that has a preference(key:value:) set using the same PreferenceKey.

reduce(value:nextValue:)

I've found that PreferenceKey's reduce(value:nextValue) will be called several times, even if there are no other Views that have a preference() with the same PreferenceKey in the View tree. And sometimes nextValue() in those calls will return a nil value. Because of this, nextValue() should do more than just

One option is to reduce based on a timestamp:

PreferenceKey Propagation Blocked by preference(key:value:)

Another issue I've found is a PreferenceKey will not get passed up through the View tree past any parent View that uses the same PreferenceKey in a preference(key:value:)

The "Red" and "Green" buttons should generate "before" and "after" messages while the "Blue" and "Yellow" buttons should only create "after" messages and all buttons should change the color. But because of the issue the "Red" and "Green" buttons don't work as expected.

A way around this is to capture the preference before using it again:

Now the "Red" and "Green" buttons work as expected.

No comments:

PreferenceKey Quirks

PreferenceKey has a few quirks that have tripped me up. One is the reduce(value:nextValue:) implementation. The other is that a PreferenceKe...