4 ms·
How does the conditional type inference work? E.g. from the article: let stack = VStack { if myState { Text("Hello") } else {
by yawaramin 7y ago
How does the conditional type inference work? E.g. from the article:
let stack = VStack {
if myState {
Text("Hello")
} else {
Rectangle()
.fill(myState ? Color.red : Color.green)
.frame(width: 100, height: 100)
}
}
Type:
VStack<
_ConditionalContent<
Text,
ModifiedContent<_ShapeView<Rectangle, Color>, _FrameLayout>>>
How does an `if` expression get inferred as a type `_ConditionalContent<...>`? Is there some magic support for SwiftUI in Swift? Does it desugar into something like:
let stack = VStack {
ConditionalContent(myState,
Text("Hello"),
Rectangle()
.fill(myState ? Color.red : Color.green)
.frame(width: 100, height: 100))
}
?
- wilg 7y agoI'd imagine so, because stuff like `if let` doesn't work.
- favorited 7y agoIt's using a not-yet-offical feature of Swift called "function builders." It's basically a way to walk through each Swift statement inside a function and build an aggregated value, including maintaining all of the type info. So the language feature isn't tied specifically to SwiftUI (though SwiftUI is the only supported client at this point), but it supports that general kind of transformation. https://github.com/apple/swift-evolution/blob/9992cf3c11c2d5e0ea20bee98657d93902d5b174/proposals/XXXX-function-builders.md https://github.com/apple/swift-evolution/blob/9992cf3c11c2d5...
- yawaramin 7y agoOh that's interesting, thanks! It seems almost perfectly designed to fit SwiftUI's use case. I wonder what other use cases it enables.
- favorited 7y agoPeople have done some cool stuff with it! My favorite is this one, which builds an NSAttributedString: https://github.com/ethanhuang13/NSAttributedStringBuilder https://github.com/ethanhuang13/NSAttributedStringBuilder
- yawaramin 7y agoOh, very cool. And now that I think about it, this can be used to make all sorts of builders. E.g. SQL comes to mind. Something like: let query = Sql { Select(["baz.foo", "quux.bar"]) From("baz") InnerJoin("quux") On(Eq("baz.id", "quux.id")) }