Swift是否会短路诸如Any或All的高阶函数? [英] Does Swift have short-circuiting higher-order functions like Any or All?

查看:114
本文介绍了Swift是否会短路诸如Any或All的高阶函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道Swift的高阶函数(例如Map,Filter,Reduce和FlatMap),但我不知道像"All"或"Any"之类的任何函数,它们在正向测试中返回短路的布尔值同时枚举结果.

I'm aware of Swift's higher-order functions like Map, Filter, Reduce and FlatMap, but I'm not aware of any like 'All' or 'Any' which return a boolean that short-circuit on a positive test while enumerating the results.

例如,假设您有10,000个对象的集合,每个对象都有一个名为isFulfilled的属性,并且您想查看该集合中是否有任何isFulfilled设置为false.在C#中,您可以使用myObjects.Any(obj -> !obj.isFulfilled),并且在达到该条件时,它将使其余的枚举短路,并立即返回true.

For instance, consider you having a collection of 10,000 objects, each with a property called isFulfilled and you want to see if any in that collection have isFulfilled set to false. In C#, you could use myObjects.Any(obj -> !obj.isFulfilled) and when that condition was hit, it would short-circuit the rest of the enumeration and immediately return true.

Swift中有这样的东西吗?

Is there any such thing in Swift?

推荐答案

Sequence(尤其是CollectionArray)具有(短路)

Sequence (and in particular Collection and Array) has a (short-circuiting) contains(where:) method taking a boolean predicate as argument. For example,

if array.contains(where: { $0 % 2 == 0 })

检查数组是否包含任何个偶数.

checks if the array contains any even number.

没有全部"方法,但是您也可以使用contains() 通过否定谓词和结果.例如,

There is no "all" method, but you can use contains() as well by negating both the predicate and the result. For example,

if !array.contains(where: { $0 % 2 != 0 })

检查数组中的所有个数字是否为偶数.当然,您可以定义一个自定义扩展方法:

checks if all numbers in the array are even. Of course you can define a custom extension method:

extension Sequence {
    func allSatisfy(_ predicate: (Iterator.Element) -> Bool) -> Bool {
        return !contains(where: { !predicate($0) } )
    }
}

如果您希望以与抛出"谓词相同的方式允许抛出"谓词 contains方法,则将其定义为

If you want to allow "throwing" predicates in the same way as the contains method then it would be defined as

extension Sequence {
    func allSatisfy(_ predicate: (Iterator.Element) throws -> Bool) rethrows -> Bool {
        return try !contains(where: { try !predicate($0) } )
    }
}

更新:正如詹姆斯·夏皮罗(James Shapiro)正确注意到的那样,allSatisfy方法已添加到 Swift 4.2 (当前为Beta)中的Sequence类型,请参见

Update: As James Shapiro correctly noticed, an allSatisfy method has been added to the Sequence type in Swift 4.2 (currently in beta), see

(需要最新的4.2开发者快照.)

(Requires a recent 4.2 developer snapshot.)

这篇关于Swift是否会短路诸如Any或All的高阶函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆