我已经坚持了好几天,试图找出问题所在。
我已经建立了一个视图,其中列出了可以放入并使用核心数据保存的数据。
我可以将数据添加到列表中,然后将其全部读回,没有任何问题,但是当我尝试过滤获取的结果时,出现标题中的错误。该错误大约是代码的一半。import CoreData
struct CollectionRow: View {
var collectionDate = Date()
let dateFormatter = DateFormatter()
var body: some View {
dateFormatter.dateStyle = .short
dateFormatter.locale = Locale(identifier: "en_GB")
return Text(dateFormatter.string(from: collectionDate))
}
}
struct CollectionList: View {
var hospital = Hospital()
@Environment(\.managedObjectContext) var managedObjectContext
@FetchRequest(
entity: Collection.entity(),
sortDescriptors: [
NSSortDescriptor(keyPath: \Collection.date, ascending: true)
]
) var collections: FetchedResults<Collection>
@State private var collectionName = ""
var body: some View {
NavigationView {
List {
VStack {
ForEach(collections, id: \.self) { collection in //Unable to infer complex closure return type; add explicit type to disambiguate
if self.hospital.id == collection.hospital {
NavigationLink(destination: CollectionRow(collectionDate: Date())){
CollectionRow(collectionDate: Date())
}
}
}
TextField("Test", text: $collectionName)
Button(action: {
let col = Collection(context: self.managedObjectContext)
col.date = Date()
col.id = Int16(self.collections.endIndex + 1)
col.hospital = self.hospital.id
self.hospital.addToHospToCol(col)
do {
try self.managedObjectContext.save()
} catch {
print(error)
}
self.collectionName = ""
}) {
Text("New Collection")
}
}
}
.navigationBarTitle(Text((hospital.name ?? "") + " - " + String(hospital.id)))
}
}
}
编辑:官方教程在ForEach中使用if语句,所以为什么不能呢?
ForEach(landmarkData) { landmark in
if !self.showFavoritesOnly || landmark.isFavorite {
NavigationLink(destination: LandmarkDetail(landmark: landmark)) {
LandmarkRow(landmark: landmark)
}
}
}
答案 0 :(得分:0)
if/else
仅可在@ViewBuilder
闭包内使用,因此ForEach
失败。
有关函数构建器here的更多信息。
一个简单的解决方案是像这样包装您的代码:
struct ForEachBuilder<Content>: View where Content: View {
private let content: Content
init(@ViewBuilder content: () -> Content) {
self.content = content()
}
var body: some View {
content
}
}
您的ForEach
将变为:
ForEach(collections, id: \.self) { collection in
ForEachBuilder {
if self.hospital.id == collection.hospital {
// Your navigation link
}
}
}