Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

swift - how to check if an array contains nth time a string?

Tags:

arrays

swift

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" ?

like image 710
l.b.dev Avatar asked Dec 14 '22 01:12

l.b.dev


2 Answers

In Swift this can be find out with just a single line of code :

myArray.filter{$0 == "a"}.count 

Hope it helps. Enjoy Coding

like image 138
Shobhakar Tiwari Avatar answered Dec 16 '22 13:12

Shobhakar Tiwari


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")
like image 30
dfrib Avatar answered Dec 16 '22 14:12

dfrib