【问题标题】:SwiftUI and The compiler is unable to type-check this expression in reasonable timeSwiftUI 和编译器无法在合理的时间内对该表达式进行类型检查
【发布时间】:2020-06-30 19:50:09
【问题描述】:

我正在尝试使用 SwiftUI 和核心数据实现列表视图,但遇到了“编译器无法在合理的时间内对该表达式进行类型检查”错误。该列表包含“课程”,每种“类型”的课程都会导致不同类型的游戏,但是,当我输入导致相关游戏链接的 if 和 else if 条件时会出现错误。我从其他帖子中了解到,代码应该被分解成更简单的部分,但我想知道最好的方法是什么,特别是对于条件语句。我尝试过的一种方法是使用特定的@FetchRequests 一次提取一个特定的课程,虽然这可以填充列表,但当从另一个视图更新实体时会产生意外行为。有关该问题的更多详细信息,请参见此处:SwiftUI List View not updating after Core Data entity updated in another View。对于如何简化此代码或如何避免此错误的任何建议,我将不胜感激。顺便说一下,这个错误只有在使用核心数据时才会出现;当我通过使用 swift 文件中的类直接“硬编码”对象时,不会出现此错误。

import SwiftUI
import CoreData
import UIKit

struct LessonList: View {

@Environment(\.managedObjectContext) var moc
@FetchRequest(entity: Lesson.entity(), sortDescriptors: []) var lessons: FetchedResults<Lesson>

var body: some View {

    NavigationView {

        List {
            Section(header: Text("Test")) {
                ForEach(lessons) { lesson in
                    if (lesson.stage == 1) && (lesson.type == "phonicIntro") {
                        NavigationLink(destination: PhonicIntroGame(lesson: lesson)) {
                            LessonRow(lesson: lesson)
                        }
                    } else if (lesson.stage == 1) && (lesson.type == "phonicDrag") {
                        NavigationLink(destination: PhonicDragGame(lesson: lesson)) {
                            LessonRow(lesson: lesson)
                        }
                    }
                }
            }
        }
        .navigationBarTitle("Lessons")            
    }
}//end of body

【问题讨论】:

    标签: swift core-data swiftui


    【解决方案1】:

    这样的错误是一个很好的指标,可以将您的视图分解为更简单的部分,例如(唯一的想法,`因为我无法编译它)

    ForEach(lessons) { lesson in
        self.lessonRow(for: lesson)
    }
    
    ...
    
    private func lessonRow(for lesson: Lesson) -> some View {
      Group {
        if (lesson.stage == 1) && (lesson.type == "phonicIntro") {
            NavigationLink(destination: PhonicIntroGame(lesson: lesson)) {
                LessonRow(lesson: lesson)
            }
        } else if (lesson.stage == 1) && (lesson.type == "phonicDrag") {
            NavigationLink(destination: PhonicDragGame(lesson: lesson)) {
                LessonRow(lesson: lesson)
            }
        }
      }
    }
    

    【讨论】:

    • 非常感谢。那工作得很好。我还有很多东西要学。
    猜你喜欢
    • 2021-10-26
    • 2020-02-14
    • 1970-01-01
    • 1970-01-01
    • 2019-12-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-20
    相关资源
    最近更新 更多