SwiftUI和编译器无法在合理的时间对该表达式进行类型检查

时间:2020-03-19 16:25:21

标签: swift core-data swiftui

我正在尝试使用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

1 个答案:

答案 0 :(得分:5)

这样的错误是将您的视图分解为更简单的部分的一个很好的指示,例如(仅出于主意,因为我无法编译此部分)

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)
        }
    }
  }
}