【问题标题】:SwiftUI: Function declares an opaque return type, but the return statements in its body do not have matching underlying typesSwiftUI:函数声明了一个不透明的返回类型,但其主体中的返回语句没有匹配的底层类型
【发布时间】:2020-10-29 08:24:19
【问题描述】:

我试图写一个这样的静态函数:

enum NavigationViewKind {
    case test1(String)
    case test2
}

struct NavigationViewManager {
    static func make<V: View>(_ kind: NavigationViewKind, _ contentView: @escaping () -> V) -> some View {
        switch kind {
        case .test1(let text):
            return NavigationView {
                contentView()
                    .navigationBarTitle(text, displayMode: .inline)
            }
        case .test2:
            return NavigationView {
                contentView()
                    .navigationBarTitle("Initial", displayMode: .large)
            }
        }
    }
}

但是我收到了这个错误:

函数声明了一个不透明的返回类型,但其主体中的返回语句没有匹配的底层类型

你能帮我理解和解决这个错误吗?

谢谢

【问题讨论】:

    标签: swift swiftui


    【解决方案1】:

    在这种情况下您需要使用@ViewBuilder(并删除返回,因为返回会禁用 ViewBuilder)

    struct NavigationViewManager {
        @ViewBuilder
        static func make<V: View>(_ kind: NavigationViewKind, _ contentView: @escaping () -> V) -> some View {
            switch kind {
            case .test1(let text):
                NavigationView {
                    contentView()
                        .navigationBarTitle(text, displayMode: .inline)
                }
            case .test2:
                NavigationView {
                    contentView()
                        .navigationBarTitle("Initial", displayMode: .large)
                }
            }
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2021-08-28
      • 1970-01-01
      • 1970-01-01
      • 2015-02-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-10-23
      相关资源
      最近更新 更多