swiftfilterfunctional-programmingcontainsswift-keypath

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


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?


Solution

  • 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)