phil
phil

Reputation: 1003

In Swiftui, I have an array that is @Published. I use .filter on the array but get error that member elements does not exist

The object definition is:

struct Course: Identifiable, Hashable, Codable {
  @DocumentID var id: String?
  var country: String
  var createdBy: String
}

I then embed this object as a member of a class as so:

class CourseRepository: ObservableObject {
    
    private let path: String = "Courses"
    private let store = Firestore.firestore()

    @Published var courses: [Course] = []
...

In the snippet below, I only want the map result to contain courses where 'createdBy' == to the uid of the currently logged in user. But on the .filter statement, I get the following error:
emphasized text

**Value of type 'Published<[Course]>.Publisher.Output' (aka 'Array<Course>') has no member 'createdBy'**


MyCourseRepository.$courses
        .filter { $0.createdBy ==  self.authState.loggedInUser!.uid }
        .map { courses in courses.map(CourseViewModel.init)}
        .assign(to: \.MyCourseViewModels, on: self)
        .store(in: &cancellables)

}

Any help on this one much appreciated!

Upvotes: 0

Views: 381

Answers (1)

jnpdx
jnpdx

Reputation: 52397

Right now, you're trying to filter the Publisher, whereas what you want to do is filter the items in the array that it's sending:

MyCourseRepository.$courses
  .map { courseArray in 
         courseArray.filter { course in 
            course.createdBy == self.authState.loggedInUser!.uid
         }
  }

Upvotes: 1

Related Questions