Flatten TupleViews using SwiftUI

Rob*_*son 3 ios swift swiftui

Ok, SwiftUI was released this week so we're all n00bs but... I have the following test code:

var body: some View {
    switch shape {
    case .oneCircle:
        return ZStack {
            Circle().fill(Color.red)
        }
    case .twoCircles:
        return ZStack {
            Circle().fill(Color.green)
            Circle().fill(Color.blue)
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

which produces the following error:

Function declares an opaque return type, but the return statements in its body do not have matching underlying types

This happens because the first ZStack is this type:

ZStack<ShapeView<Circle, Color>>
Run Code Online (Sandbox Code Playgroud)

and the second is this type:

ZStack<TupleView<(ShapeView<Circle, Color>, ShapeView<Circle, Color>)>>
Run Code Online (Sandbox Code Playgroud)

How do I deal with this in SwiftUI? Can they be flattened somehow or be made to conform to the same type.

rob*_*off 8

解决此问题的一种方法是使用类型橡皮擦AnyView

var body: some View {
    switch shape {
    case .oneCircle:
        return AnyView(ZStack {
            Circle().fill(Color.red)
        })
    case .twoCircles:
        return AnyView(ZStack {
            Circle().fill(Color.green)
            Circle().fill(Color.blue)
        })
    }
}
Run Code Online (Sandbox Code Playgroud)