SwiftUI 核心数据,分组列表获取结果

标签 swift core-data swiftui

使用核心数据我存储一些机场和每个机场我存储不同的笔记
我创建了实体机场和实体简报
Airport 有 1 个属性称为 caoAPT,而 Briefing 有 4 个属性 category、descript、icaoAPT、noteID
在我的 detailsView 上,我显示了与该机场相关的所有注意事项的列表,我设法通过另一个名为 FilterList 的 View 进行了动态获取

import SwiftUI
import CoreData


struct FilterLIst: View {
    var fetchRequest: FetchRequest<Briefing>
    @Environment(\.managedObjectContext) var dbContext
    
    
    init(filter: String) {
        fetchRequest = FetchRequest<Briefing>(entity: Briefing.entity(), sortDescriptors: [], predicate: NSPredicate(format: "airportRel.icaoAPT == %@", filter))
        
    }
    func update(_ result : FetchedResults<Briefing>) ->[[Briefing]]{
        return Dictionary(grouping: result) { (sequence : Briefing)  in
            sequence.category
        }.values.map{$0}
        
    }
    

        
  
    var body: some View {
       
        List{
            ForEach(update(self.fetchRequest.wrappedValue), id: \.self) { (section : Briefing) in
                Section(header: Text(section.category!)) {
                    
                    ForEach(section, id: \.self) { note in
                        Text("hello") 
/// Xcode error Cannot convert value of type 'Text' to closure result type '_'
                    }
                }
            }
        }
    }
}

在此 View 中,我尝试使用 func update 显示按类别划分的所有部分...
但是 Xcode 给了我这个错误,我不明白为什么..无法将“Text”类型的值转换为关闭结果类型“_”
前引用我在我的详细信息下面列出
import SwiftUI

struct DeatailsView: View {
    @Environment(\.managedObjectContext) var dbContext
    @Environment(\.presentationMode) var presentation
    @State var airport : Airport
    @State var note = ""
    @State var noteTitle = ["SAFTY NOTE", "TAXI NOTE", "CPNOTE"]
    @State var notaTitleSelected : Int = 0
    @State var notaID = ""

    
    
    
    var body: some View {
        Form{
            Section(header: Text("ADD NOTE Section")) {
                TextField("notaID", text: self.$notaID)
                    .textFieldStyle(RoundedBorderTextFieldStyle())
                    .padding()
                TextField("add Note descrip", text: self.$note)
                    .textFieldStyle(RoundedBorderTextFieldStyle())
                    .padding()
                
                Picker(selection: $notaTitleSelected, label: Text("Class of Note")) {
                    ForEach(0 ..< noteTitle.count) {
                        Text(self.noteTitle[$0])
                    }
                }
                HStack{
                    Spacer()
                    Button(action: {
                        let nota = Briefing(context: self.dbContext)
                        nota.airportRel = self.airport
                        nota.icaoAPT = self.airport.icaoAPT
                        nota.descript = self.note
                        nota.category = self.noteTitle[self.notaTitleSelected]
                        nota.noteID = self.notaID
                        
                        do {
                            try self.dbContext.save()
                            debugPrint("salvato notazione")
                            
                        } catch {
                            print("errore nel salva")
                        }
                    }) {
                        Text("Salva NOTA")
                    }
                    Spacer()
                }
            }
            
            Section(header: Text("View Note")) {
                FilterLIst(filter:  airport.icaoAPT ?? "NA")
            }
        }
    }
}
谢谢您的帮助

最佳答案

这是因为您尝试迭代单个 Briefing对象和 ForEach循环需要一个集合:

List {
    ForEach(update(self.fetchRequest.wrappedValue), id: \.self) { (section: Briefing) in
        Section(header: Text(section.category!)) {
            ForEach(section, id: \.self) { note in // <- section is a single object
                Text("hello")
                /// Xcode error Cannot convert value of type 'Text' to closure result type '_'
            }
        }
    }
}
我建议您提取第二个 ForEach为清楚起见,另一种方法。通过这种方式,您还可以确保传递的是正确类型的参数 ( [Briefing] ):
func categoryView(section: [Briefing]) -> some View {
    ForEach(section, id: \.self) { briefing in
        Text("hello")
    }
}
请注意,您的 update 的结果方法的类型为 [[Briefing]] , 表示 ForEach 中的参数是 section: [Briefing] (而不是 Briefing ):
var body: some View {
    let data: [[Briefing]] = update(self.fetchRequest.wrappedValue)
    return List {
        ForEach(data, id: \.self) { (section: [Briefing]) in
            Section(header: Text("")) { // <- can't be `section.category!`
                self.categoryView(section: section)
            }
        }
    }
}
这也意味着你不能写 section.category!在标题中作为 section是一个数组。
您可能需要访问 Briefing获取类别的对象:
Text(section[0].category!)
(如果您确定第一个元素存在)。

为了清楚起见,我明确指定了类型。这也是确保始终使用正确类型的好方法。
let data: [[Briefing]] = update(self.fetchRequest.wrappedValue)
但是,Swift 可以自动推断类型。在下面的示例中,data类型为 [[Briefing]] :
let data = update(self.fetchRequest.wrappedValue)

关于SwiftUI 核心数据,分组列表获取结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62727370/

相关文章:

swift - 如何在没有内存警告的情况下快速从Web服务加载图像

ios - UITextField 自定义清除按钮

swift - 如何从字典中查找值

ios - 使用 UiButton 反复更改 UILabel 文本

swift - 如何使 SwiftUI 列表自动滚动?

iphone - iOS 开发 : Can I store an array of integers in a Core Data object without creating a new table to represent the array?

ios - 将 QLPreviewController 与 Core Data 结合使用的正确方法

iphone - 核心数据: does a fetch have to make a trip to persistent store?

swift - SwiftUI 中按钮和图像的可点击区域

swiftui - 将数组传递给另一个 View SwiftUI