Swift 2 Read array negotiation state elements

Basically I am looking for a quick equivalent of the following C ++ code:

std::count_if(list.begin(), list.end(), [](int a){ return a % 2 == 0; }); // counts instances of even numbers in list

My problem is not really finding even numbers; just a general case of counting instances matching the criteria.

I did not see the built-in, but would like to hear that I just missed it.

+5
source share
6 answers

Like this:

 let a: [Int] = ...
 let count = a.filter({ $0 % 2 == 0 }).count
+21
source

Alternative version of Aderstedt

let a = [ .... ]
let count = a.reduce(0){ 
    (count, element) in 
    return count + 1 - element % 2
}

My intuition says that my path will be faster, because it does not require the creation of a second array. However, you need to check both methods.

Edit

Following MartinR's comment on function generalization, here

extension SequenceType
{
    func countMatchingCondition(condition: (Self.Generator.Element) -> Bool) -> Int
    {
        return self.reduce(0, combine: { (count, e) in count + (condition(e) ? 1 : 0) })
    }
}

let a = [1, 2, 3, 3, 4, 12].countMatchingCondition { $0 % 2 == 0 }
print("\(a)") // Prints 3
+9
source

, :

let a = Array(1 ... 20)
let evencount = a.reduce(0) { $0 + ($1 % 2 == 0 ? 1 : 0) }

: 0 (var $0), a (var $1), 2 , .

, , a.filter() {}. count.

+3

reduce()

let a = Array(1 ... 20)
let evenCount = a.reduce(0) { (accumulator, value) -> Int in
    guard value % 2 == 0 else { return accumulator }
    return accumulator + 1
}

Almost everything that you want to do with functions map()and filtercan be done with reduce, although it is not always the most readable one.

+2
source

You can use Collection.lazy to have Aderstedt's answer simplicity, but with an O (1) space.

let array = [1, 2, 3]
let count = array.lazy.filter({ $0 % 2 == 0 }).count
0
source

The default array is:

let array: [Int] = [10, 10, 2, 10, 1, 2, 3]

Swift 5 with the score (where :)

let countOfTen = array.count(where: { $0 == 10 }) // 3

Swift 4 or less with filter (_ :)

let countOfTen = array.filter({ $0 == 10 }).count // 3
0
source

Source: https://habr.com/ru/post/1610318/


All Articles