首页 > 解决方案 > Swiftui seems not to work correctly with Cocoapods and Firebase

问题描述

I'm trying to create an iOS App using SwiftUI. My data is stored within a Google Firebase realtime database. I fetch my data to an ObservableObject so that the UI can be loaded dynamically, if data get's added or removed. But for some reason I always getting the error "Type of expression is ambiguous without more context" for a Text().

I've already tried to remove the if statements and the Text() but then I'm getting errors in other places. E.g. I also have to write

HStack{ ... }.padding(.leading, CGFloat(20))

If I do not cast 20 to a CGFloat I'm getting the error "'CGFloat' is not convertible to 'CGFloat?'". I know that SwiftUI's error messages aren't that good yet since almost 90% of code failures leads to some ambiguous bla errors. But here I really don't know where these errors are coming from.

import SwiftUI

struct IngredientsTab: View {

    @ObservedObject var ingredientsVM: IngredientViewModel = IngredientViewModel()

    var body: some View {

        NavigationView {
            List {
                ForEach(ingredientsVM.ingredients, id: \.self){ (ingredient) in
                    NavigationLink(destination: IngredientDetailView(ingredient: ingredient)){
                        VStack {
                            HStack {
                                Text(ingredient.name)
                                Spacer()

                                if (Type.NONALC == ingredient.type) {
                                    self.modifier(LabelViewModifier(label: "Non-alcoholic", backgroundColor: .green))
                                } else {
                                    self.modifier(LabelViewModifier(label: "Alcoholic", backgroundColor: .red))
                                }
                            }

                            if (ingredient.pieceGood) {

                                HStack {
                                    Image(systemName: "checkmark.circle.fill")
                                        .foregroundColor(Color.green)
                                    Text("Piece good") // Here I'm getting the error
                                    Spacer()
                                }
                                .padding(.leading, 20)
                            }
                        }
                    }
                }
            }
        }
    }
}

So it seems to be somehow related to SwiftUI (since it is obviously not working perfectly yet) but also to Cocoapods/ Firebase. In another project I have a similar approach but without using any Pods and it is just working fine.

标签: iosswiftfirebase-realtime-databasecocoapodsswiftui

解决方案


我终于找到了问题所在。我的成分继承自 Identifiable 也继承自 NSObject。结合一些错误的构造函数和写作

id: \.self

在 ForEach 循环中导致了这种奇怪的行为。我将我的成分更新为正确的模型,并从 ForEach 循环中删除了上面的行,然后它就起作用了。

谢谢您的帮助!

PS:它既不与任何 Pod 相关,也不与 Firebase 相关;)


推荐阅读