Issue #817
Thanks to resultBuilder
and container type in Swift, the following are possible in SwiftUI
Local variable
struct ChartView {
var body: some View {
computation
}
@ViewBuilder
var computation: some View {
let left = 10
let right = 20
if left + right == 30 {
Text("Correct")
}
}
}
if and switch statement
struct ChartView: View {
@State private var showsOverlay: Bool = false
@State private var overlayKind: OverlayKind?
enum OverlayKind {
case weather(String)
}
var body: some View {
VStack {
EmptyView()
}
.overlay(
overlayView
)
}
@ViewBuilder
private var overlayView: some View {
if showsOverlay, let overlayKind = overlayKind {
switch overlayKind {
case let .weather(city):
WeatherView(city: city)
}
}
}
}
If statement only
struct ChartView: View {
@State private var showsLegend: Bool = false
var body: some View {
if showsLegend {
LegendView()
}
}
}
Empty return
struct ChartView: View {
var body: some View {
Text("Chart View")
footer()
}
@ViewBuilder
func footer() -> some View {
}
}
Return nil
Optional
conforms to View
, see Optional
Conforms when Wrapped conforms to View.
struct ChartView: View {
let decorations: [String: AnyView]
var body: some View {
border
borderColor
decoration
}
var borderColor: Color? {
nil
}
var border: Rectangle? {
nil
}
@ViewBuilder
var decoration: some View {
decorations["N/A"]
}
}