Static Types in SwiftUI
Chris Eidhof (tweet, Hacker News):
In SwiftUI, the implementation works differently. In our
stack
above, SwiftUI knows the type: a vertical stack view with two subviews. During the execution of the program this type will never change — it’s a static property of the code. As such, our program will always render a vertical stack view with a text and a rectangle. When the state changes, some of the views’ properties might change, but the stack view with the two subviews will always persist.This hard guarantee from the type system means that SwiftUI doesn’t need to do a tree diff. Instead, it only needs to look at the properties of each view, and update those on screen. Theoretically, this still involves walking the entire tree, but walking a tree has a much lower complexity than diffing a tree.
[…]
For view trees that have a variable length, SwiftUI uses
ForEach
. We won’t go into detail onForEach
, but SwiftUI requires you to provide either a constant range, or, if the length is truly dynamic, to use an identifier for each element you’re displaying. When the elements change,ForEach
uses the identifier to uniquely identify elements during a diffing step.[…]
An
AnyView
is a type-erased view, and as such, it provides no information at compile-time about what’s inside. SwiftUI will need to do more work at runtime to verify changes (as mentioned here, and here).
1 Comment RSS · Twitter
SwiftUI is just a monoid in the category of endofunctors, what's the problem?