In Swift how would I iterate through the NSMutableArray of ints var numbers = [4,5,5,4,3] and count how many are equal to 5?
2 Answers
You can use reduce for this:
let array = [4,5,5,4,3]
let fives = array.reduce(0, combine: { $0 + Int($1 == 5) })
5 Comments
colindunn
Is this compatible with NSMutableArray?
Sebastian
Yes, with casting to a Swift array. Otherwise use a method profided by
NSMutableArray.Sebastian
That should have been "provided" ;)
Dániel Nagy
I didn't know that you can use boolean literals in the constructor of Int, very classy, this should be the accepted answer.
rintaro
Note that
Int($1 == 5) invokes init(_ number: NSNumber) initializer defined in Foundation.One possible solution:
numbers.filter {$0 == 5}.count
2 Comments
colindunn
Where
a equals the name of the array?Dániel Nagy
Yes, it is, I just didn't described it.
var numbers = [4,5,5,4,3]is not of typeNSMutableArray. Major difference is that it is a value type and not a reference to an object. Said that, I upvoted the @ Sebastian Dressler solution.