0

array.filtered does not exist in Swift anymore, I am looking for a way to use 'IN' operator in array.filter closure same as how I used it with NSPredicate.

Before the query was something like

let predicate = NSPredicate(format: "(user in %@)", overallUsers)
tasksArray.filtered(using: predicate)

Now this cannot be used with swift4, so how can I achieve the same with array.filter{} ? I tried something like this

tasksArray.filter{$0.user in overallUsers}

This fails with error 'Cannot convert value of type '@lvalue User' to closure result type 'Bool''. How this should be actually done ?

Eric Aya
  • 69,473
  • 35
  • 181
  • 253
XiOS
  • 1,665
  • 2
  • 18
  • 22
  • You want to filter overallUsers? – Rakesh Patel Dec 12 '18 at 12:13
  • Possible duplicate of [How to get list of common elements of 2 array in Swift?](https://stackoverflow.com/questions/32439289/how-to-get-list-of-common-elements-of-2-array-in-swift) – ielyamani Dec 12 '18 at 14:30
  • You can't translate word for word a `NSPredicate` format. You have to ask you this: "What means "something in someArray" in a NSPredicate"? If someArray contains something. Then, just write the corresponding "Swift" code. – Larme Dec 12 '18 at 16:38

2 Answers2

1

Instead of tasksArray.filter{$0.user in overallUsers} you need something like this:

tasksArray.filter { task in
    overallUsers.contains(task.user)
}

Requirement: User has to conform to Equatable.

André Slotta
  • 13,774
  • 2
  • 22
  • 34
1

You can check it like this.

taskArray.filter( { overallUsers.contains($0.user) } )
Rakesha Shastri
  • 11,053
  • 3
  • 37
  • 50