首页 > 解决方案 > Swift:.contains(where:) 使用键路径表达式

问题描述

有没有办法使用键路径表达式来简化 Swift 中的样板代码contains(where:)?

例如

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

上面的例子是否可以在 Swift 中表达,使用\.boolon struct Struct,而不诉诸于structs.filter(\.bool).count > 0

标签: swiftfilterfunctional-programmingcontainsswift-keypath

解决方案


是的,您只需要在contains(where:)没有闭包的情况下将 key-path 传递给,就像您使用filter.

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

推荐阅读