微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

无法调用非函数类型“[成分]”的值

如何解决无法调用非函数类型“[成分]”的值

我收到错误无法调用函数类型“[Ingredient]”的值,不知道为什么。

在 Main.xcdatamodeld 中创建的 My Recipe 类包含许多关于任何配方的数据,包括 名称:字符串

我有一个创建 Recipe 扩展的文件,其中包括

python3 -v

我有一个结构 RecipeListView,它调用 RecipeDetailView。 RecipeDetailView的调用如下:

extension Recipe {

    enum SortOrder {
        case title,category
    }

    var recipeName: String {
        name ?? ""
    }

    var recipeIngredients: [Ingredient] {
        ingredients?.allObjects as? [Ingredient] ?? []
    }
}

在 RecipeDetailView 中,我试图列出所选配方(传入的)的成分,如:

import SwiftUI

struct RecipeListView: View {
    @EnvironmentObject var dataController: DataController
    @Environment(\.managedobjectContext) var managedobjectContext
    @State private var sortOrder = Recipe.sortOrder.title

    let recipes: FetchRequest<Recipe>

    init() {
        recipes = FetchRequest<Recipe>(entity: Recipe.entity(),sortDescriptors: [
            NSSortDescriptor(keyPath: \Recipe.name,ascending: true)
        ])
    }
        
    var body: some View {
        NavigationView {
            ScrollView {
                vstack(alignment: .leading) {
                    ForEach(recipes.wrappedValue) { recipe in
                        NavigationLink(destination:
RecipeDetailView(recipe: recipe)) {
                            Text(recipe.recipeName)
                                .padding([.horizontal])
                        }
                    }
                }
            }
            .navigationTitle("Recipes")
        }
    }
}

在 ForEach 行上,我收到错误消息(recipeIngredients 中 c 下的标记),但 recipe 是通过调用传入的,并且 recipe.recipeIngredients 和 sortOrder 在扩展中定义。而且,成分名称在 Main.xcdatamodeld 中定义。 我尝试在 init 中添加一行“var selectedRecipe = recipe”,然后在 ForEach 中使用 selectedRecipe.recipeIngredients。我已经尝试过 recipe.ingredient 和 recipe.recipeIngredient 作为 ForEach 的用途。我试过在 recipe.ingredients 和成分上做 ForEach。一切都无济于事。似乎错误告诉我我需要在 ForEach 中调用函数,这毫无意义。任何帮助表示赞赏。 谢谢, 账单

解决方法

你有房产

var recipeIngredients: [Ingredient] {
    ingredients?.allObjects as? [Ingredient] ?? []
}

但是在您的 ForEach 中,您像调用函数一样调用它

ForEach(recipe.recipeIngredients(using: sortOrder)) {

所以错误信息很有意义。所以首先将其更改为

ForEach(recipe.recipeIngredients) {

并提前对其进行排序或执行类似操作

ForEach(recipe.recipeIngredients.sorted(by: { <your sort logic here> }) {

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。