swift - 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 中表达,使用\.bool
on struct Struct
,而不诉诸于structs.filter(\.bool).count > 0
?
解决方案
是的,您只需要在contains(where:)
没有闭包的情况下将 key-path 传递给,就像您使用filter
.
let hasTruth = structs.contains(where: \.bool)
推荐阅读
- java - 从 main 调用的参数化 JUnit 测试
- python-2.7 - 如何使用 tfidf python 转换数据
- python - 在 Flask 中使用请求参数作为变量 URL,第二个值返回为 none
- firebase - Firebase:如何防止在 Firestore 中写入特定字段?
- list - 使用哪个函数在 kotlin 中制作列表的副本
- android - 如何使用复选框来确定显示或跳过入职屏幕?
- java - Eclipse 在多个项目上运行不同的 Maven 目标
- git - 包含斜杠的分支名称的 Stash GIT API 是什么?
- c# - Cefsharp 不显示图像
- logparser - ORDER BY 不同方向的多列(ASC 和 DESC)