什么是斯威夫特的同行JavaScript的Array.some()和Array.every()? [英] What are Swift's counterparts to JavaScript's Array.some() and Array.every()?

查看:264
本文介绍了什么是斯威夫特的同行JavaScript的Array.some()和Array.every()?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

斯威夫特提供地图过滤减少,为... 阵列的,但我没有找到部分(或)或每个(或所有),其在同行中的JavaScript是的 Array.some 阵列。每 。我不能看着够硬还是他们存在?

Swift provides map, filter, reduce, ... for Array's, but I am not finding some (or any) or every (or all) whose counterparts in JavaScript are Array.some and Array.every. Am I not looking hard enough or do they exist?

A <一个href=\"http://stackoverflow.com/questions/35061150/what-is-the-swift-equivalent-of-c-net-linqs-enumerable-all-method\">related这里问题是寻找雨燕所有方法,但JS程序员可能会找不到它(有没有所有在JS和部分任何未提及)。

A related question here is looking for the Swift all method, but JS programmers will probably not find it (there is no all in JS and some or any is not mentioned).

推荐答案

要替换任何 / 部分,你可以使用序列类型的<一个href=\"https://developer.apple.com/library/tvos/documentation/Swift/Reference/Swift_SequenceType_Protocol/index.html#//apple_ref/swift/intfm/SequenceType/s:FEsPs12SequenceType8containsFzFzWx9Generator7Element_SbSb\"相对=nofollow> 包含 方法(还有一个版本,它接受一个布尔值predicate;另一种需要的元素,仅适用于序列Equatable元素)。

To replace any/some, you can use SequenceType's contains method (there's one version which takes a boolean predicate; the other one takes an element and works only for sequences of Equatable elements).

有像没有内置的功能所有 / 每个,但你可以轻松地将自己的使用延长写

There's no built-in function like all/every, but you can easily write your own using an extension:

extension SequenceType
{
    /// Returns `true` iff *every* element in `self` satisfies `predicate`.
    func all(@noescape predicate: Generator.Element throws -> Bool) rethrows -> Bool
    {
        for element in self {
            if try !predicate(element) {
                return false
            }
        }
        return true
    }
}

或者,由于德·摩根<​​/A>,你可以否定<$结果C $ C>包含:{!predicate($ 0)}。 array.contains

Or, thanks to De Morgan, you can just negate the result of contains: !array.contains{ !predicate($0) }.

顺便说一句,在任何序列类型,而不仅仅是阵列这些工作。这包括设定,甚至词典(其元素是(键,值)元组)。

By the way, these work on any SequenceType, not just Array. That includes Set and even Dictionary (whose elements are (key, value) tuples).

这篇关于什么是斯威夫特的同行JavaScript的Array.some()和Array.every()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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