let's take the array :
var myArray = ["a", "b", "c", "a", "b", "a", "b", "c", "a", "b"]
I know that you need to use .contains() to know if the array contains an objet.
myArray.contains("a") //true
But how to know if the array contains 4 times "a" ?
In Swift this can be find out with just a single line of code :
myArray.filter{$0 == "a"}.count
Hope it helps. Enjoy Coding
The filter
solution shown in other answers is neat, and fit for the purpose. I'll include a few more alternatives.
As another alternative, use a simple for ... in
loop with a where
condition holding the conditional to increase a counter:
let myArray = ["a", "b", "c", "a", "b", "a", "b", "c", "a", "b"]
var count = 0
for element in myArray where element == "a" { count += 1 }
print(count) //4
Or, as another alternative, make use of reduce
:
let myArray = ["a", "b", "c", "a", "b", "a", "b", "c", "a", "b"]
let count = myArray.reduce(0) { $0 + ($1 == "a" ? 1 : 0) }
print(count) //4
I'll also include a use example for NSCounted
set covered in @user28434's answer
import Foundation
let myArray = ["a", "b", "c", "a", "b", "a", "b", "c", "a", "b"]
let countedSet = NSCountedSet(array: myArray)
let count = countedSet.count(for: "a")
print(count) // 4
// or, simply
let count = NSCountedSet(array: myArray).count(for: "a")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With