0

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?

1
  • Just to remind you that var numbers = [4,5,5,4,3] is not of type NSMutableArray. Major difference is that it is a value type and not a reference to an object. Said that, I upvoted the @ Sebastian Dressler solution. Commented Jan 20, 2015 at 9:27

2 Answers 2

4

You can use reduce for this:

let array = [4,5,5,4,3]
let fives = array.reduce(0, combine: { $0 + Int($1 == 5) })
Sign up to request clarification or add additional context in comments.

5 Comments

Is this compatible with NSMutableArray?
Yes, with casting to a Swift array. Otherwise use a method profided by NSMutableArray.
That should have been "provided" ;)
I didn't know that you can use boolean literals in the constructor of Int, very classy, this should be the accepted answer.
Note that Int($1 == 5) invokes init(_ number: NSNumber) initializer defined in Foundation.
1

One possible solution:

numbers.filter {$0 == 5}.count

2 Comments

Where a equals the name of the array?
Yes, it is, I just didn't described it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.