Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What are Swift's counterparts to JavaScript's Array.some() and Array.every()?

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 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).

like image 681
wcochran Avatar asked Dec 18 '22 18:12

wcochran


2 Answers

Update:

Use allSatisfy (all) and contains(where:) (some).

Old answer:

Just use contains.

// check if ALL items are completed
// so it does not contain a single item which is not completed
!items.contains { !$0.completed }

// check if SOME item is completed
// so test if there is at least one item which is completed
items.contains { $0.completed }
like image 59
schirrmacher Avatar answered Feb 22 '23 23:02

schirrmacher


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
    }
}

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).

like image 26
jtbandes Avatar answered Feb 23 '23 01:02

jtbandes