什么是C#/ .NET / LINQ的Enumerable.All方法的Swift等价物? [英] What is the Swift equivalent of C#/.NET/LINQ's Enumerable.All method?

查看:257
本文介绍了什么是C#/ .NET / LINQ的Enumerable.All方法的Swift等价物?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要一个将给定函数应用于序列的函数,如果给定函数对序列的每个元素返回true,则返回true,如 Enumerable.All 来自C#/ .NET / LINQ世界。

没有一个内置的函数可以做到这一点,但是您可以轻松地将自己添加为协议扩展方法:

  extension SequenceType {
func all(@noescape谓词:(Self.Generator.Element)throws - > Bool)
rethrows - > Bool {

for self in {{b $ b if!(try predicate(i)){return false}
}
return true
}

,然后在如下序列中使用它:

  let allPositive = [1,2,3] .all {$ 0> 0} 


I want a function that applies a given function to a sequence and returns true iff the given function returns true for every element of the sequence, like Enumerable.All from the C#/.NET/LINQ world.

解决方案

There isn't a built-in function to do this, but you can easily add your own as a protocol extension method:

extension SequenceType {
    func all(@noescape predicate: (Self.Generator.Element) throws -> Bool)
        rethrows -> Bool {

        for i in self {
            if !(try predicate(i)) { return false }
        }
        return true
    }
}

and then use it on a sequence like:

let allPositive = [1, 2, 3].all { $0 > 0 }

这篇关于什么是C#/ .NET / LINQ的Enumerable.All方法的Swift等价物?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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