【问题标题】:Cannot assign value of type 'some View' to type 'some View' - why not?无法将类型 \'some View\' 的值分配给类型 \'some View\' - 为什么不呢?
【发布时间】:2022-12-12 02:43:48
【问题描述】:

我正在尝试创建一个包含弹出视图动态配置的结构。这包括一组 actionButtons 以及一个 body 属性,它们将构成稍后的弹出窗口。正文可以看作是弹出窗口的“子视图”,例如文本。我希望能够在我的初始值设定项中使用 @ViewBuilder 随意指定子视图。

但是,我收到以下错误:

Cannot assign value of type 'some View' to type 'some View' (type of 'PopupConfiguration.body')

public struct PopupConfiguration {
    let headline: String
    private(set) var body: some View = EmptyView()
    let actionButtons: [ActionButtonDefinition]

    init(headline: String, @ViewBuilder bodyContent: () -> some View, actionButtons: [ActionButtonDefinition]) {
        self.headline = headline
        self.body = bodyContent() // Cannot assign value of type 'some View' to type 'some View' (type of 'PopupConfiguration.body')
        self.actionButtons = actionButtons
    }
}

我现在很困惑,因为编译器应该能够将 some View 分配给 some View,对吧?它实际上是同一类型,还是不是?

谁能解释为什么会产生上面显示的错误?

【问题讨论】:

    标签: swift generics swiftui swift-protocols opaque-types


    【解决方案1】:

    在这种情况下,您需要使用泛型:

    public struct PopupConfiguration<Content: View> {
        let headline: String
        private(set) var body: Content
        let actionButtons: [ActionButtonDefinition]
    
        init(headline: String, @ViewBuilder bodyContent: () -> Content, actionButtons: [ActionButtonDefinition]) {
            self.headline = headline
            self.body = bodyContent()
            self.actionButtons = actionButtons
        }
    }
    

    我建议您阅读opaque types documentation,尤其是“不透明类型和协议类型之间的差异”部分:)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-01-26
      • 1970-01-01
      • 2019-12-12
      • 2017-01-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多