【问题标题】:Swift: .contains(where:) using key-path expression [duplicate]Swift:.contains(where:) 使用键路径表达式 [重复]
【发布时间】:2021-12-11 02:31:41
【问题描述】:

有没有办法使用键路径表达式来简化 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 表达,在 struct Struct 上使用 \.bool,而不使用 structs.filter(\.bool).count > 0

【问题讨论】:

  • structs.contains(where: \.bool) ???

标签: swift filter functional-programming contains swift-keypath


【解决方案1】:

是的,您只需将密钥路径传递给 contains(where:) 而无需闭包,就像使用 filter 一样。

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-02-01
    • 2021-08-18
    • 2019-03-27
    • 2012-12-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多