Michael Long
2 min readMar 4, 2023

--

The real problem, IMHO, is using Redux-style architectures with SwiftUI.

SwiftUI wants a Single Source of Truth for a given piece of data. It does not, however, want a single source of DATA for the ENTIRE application. It prefers state to be bound as low in the view hierarchy as possible, which minimizes the amount of view diffing that needs to occur when that state changes.

TCA and Redux seem like a great fit, but in reality you can run into problems where, as indicated, you're copying and passing around a huge hunk of state or when a single state change occurs and triggers a view update cycle of every single view in the system dependent on that one single chunk of state.

I wrote about a lot of those issues here:

https://medium.com/swlh/deep-inside-views-state-and-performance-in-swiftui-d23a3a44b79

Secondarily, your "What about performance" section is incorrect. Swift's COW mechanisms (plural) are complex. They basically promise value semantics, but how Swift achieves that is up to Swift. It may pass a reference. It may copy everything. It may only pass a portion of something. The internal mechanism used to achieve that varies and Swift can do as it pleases just as long as the appearance of value semantics is mantained.

Read some of the answers here:

https://stackoverflow.com/questions/43486408/does-swift-copy-on-write-for-all-structs#comment74028610_43486408

You should also beware of trying to interpret Swift behavior in the debugger, since in debug mode you're running without compiler optimizations and, as discussed, what you see in one environment may not be what you see in another.

Next, you need to be careful passing your shiny new reference around in multi-threaded environments.

https://www.wwt.com/article/swift-value-semantics-cows-and-clean-threads

And finally, I'd consider the implementation to be fragile. Swift arrays implement COW by implementing the isKnownUniquelyReferenced check in every mutating function and method that references the allocated object. Passing around a reference to single chunk of state without guarding access to changes works just as long as everyone plays by the rules.

--

--

Michael Long
Michael Long

Written by Michael Long

I write about Apple, Swift, and SwiftUI in particular, and technology in general. I'm also a Lead iOS Engineer at InRhythm, a modern digital consulting firm.

No responses yet