1

I'm learning SwiftUI at the moment. I've been playing around with loading a list from CoreData and making changes on / filtering etc. I've run into the issues below. Essentially as soon as I try to apply any conditionals within the ForEach I I'm presented with that error.

This works if I run iterate through the organisations in List itself rather than a ForEach. This isn't the ideal solution as I loose the inbuilt deletion function.

Am I missing something stupid?

let defaults = UserDefaults.standard

@EnvironmentObject var userData: UserData

@Environment(\.managedObjectContext) var managedObjectContext
@FetchRequest(entity: Organisation.entity(), sortDescriptors: [NSSortDescriptor(keyPath: \Organisation.name, ascending: true)])
var orgs: FetchedResults<Organisation>


var body: some View
{
    NavigationView {
        
        List {
            
            ForEach(orgs, id: \.self) {org in
                
                if !self.userData.showFavsOnly || org.isFavorite {
                    
                    NavigationLink(destination: OrganisationView(org: org, moc: self.managedObjectContext)) {
                        
                        OrganisationRow(org: org)
                        
                    }
                    
                }
                
            }
            
        }
        
    }
}

There error code I get is I get is on the for each line and is

Type '()' cannot conform to 'View'; only struct/enum/class types can conform to protocols

Thanks for your help

0

1 Answer 1

2

Type '()' cannot conform to 'View'; only struct/enum/class types can conform to protocols

This error means that your ForEach loop expects some View. But you give it an if-statement instead. What if the condition returns false?

The solution may be to wrap the if-statement in some View - it could be a Group, VStack, ZStack...

ForEach(orgs, id: \.self) { org in
    Group {
        if !self.userData.showFavsOnly || org.isFavorite {
            NavigationLink(destination: OrganisationView(org: org, moc: self.managedObjectContext)) {
                OrganisationRow(org: org)
            }
        }
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.