Swift: .contains(where:) using key-path expression

585 Views Asked by At

Is there someway to use a key-path expression to simplify boilerplate code in a Swift contains(where:)?

E.g.

struct Struct {
  let bool: Bool
}
let structs = [
  Struct(bool: false), 
  Struct(bool: false),
  Struct(bool: true), 
  Struct(bool: false),
  Struct(bool: false)
]
let hasTruth = structs.contains { $0.bool }
print(hasTruth) // true

Is the above example possible to express in Swift, using \.bool on the struct Struct, without resorting to structs.filter(\.bool).count > 0?

1

There are 1 best solutions below

0
Dávid Pásztor On BEST ANSWER

Yes, you simply need to pass the key-path to contains(where:) without a closure, same as you do with filter.

let hasTruth = structs.contains(where: \.bool)