-3

The following will compare the first element's id with compr's id, and return true if matched. I am confused with {} of .first { } != nil syntax. How does the longer form of this pattern condense to to the following:

private(set) var arr : [Arrs] = [] 

func isPresent(for compr: Compr) -> Bool {
  Arrs.first { comp.id == $0.id } != nil 
}
bentim
  • 45
  • 3

1 Answers1

3

First, change the line to the following so it compiles:

arr.first { compr.id == $0.id } != nil

This is just using trailing closure syntax for the first(where:) method. It can also be written as:

arr.first(where: { compr.id == $0.id }) != nil

But a better way would be to do the following:

arr.contains { compr.id == $0.id }
George
  • 19,234
  • 7
  • 57
  • 99