【发布时间】:2017-10-10 15:00:56
【问题描述】:
我刚刚在 swift 中了解了 map、flatMap 和 reduce 的美妙世界,我已经在任何有意义的地方使用它并帮助改进我的代码。
现在我遇到了一个非常特殊的问题,我想知道是否有使用 map、flatMap 和/或 reduce 的解决方案。
在我的模型类中,我有一个可选的其他模型数组。这些模型有一个可选的 Bool 属性。我现在想知道整个模型数组是否至少包含一个具有真实属性的模型。这就是我目前正在做的事情:
class ModelA{
var bModels: [ModelB]?
}
class ModelB{
var aBool: Bool?
}
func hasATrue(aModel: ModelA) {
guard let bModels = aModel.bModels else { return false }
for bModel in bModels {
if bModel.aBool == true {
return true
}
}
return false
}
【问题讨论】:
-
您正在寻找
contains(where:)- 比较stackoverflow.com/q/29679486/2976878 -
在你的情况下
return aModel.bModels?.contains(where: { $0.aBool == true }) ?? false -
或
return aModel.bModels?.contains(where: { $0.aBool == true }) == true– 更加对称:) -
你也可以使用reduce:
return aModel.bModels?.reduce(false) { $0 || $1.aBool ?? false } == true -
@paulvs:我不建议这样做。
reduce不像contains那样短路。
标签: swift dictionary reduce flatmap