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

take an array:

var myArray = ["a", "b", "c", "a", "b", "a", "b", "c", "a", "b"]

I know you need to use .contains () to find out if the array contains an objet object. myArray.contains("a") //true

But how do you know if an array contains 4 times "a"?

+4
source share
4 answers

In Swift, this can only be recognized with a single line of code:

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

Hope this helps. Enjoy coding

+5
source

The solution filtershown in the other answers is neat and suitable for this purpose. I will include some more alternatives.


As another alternative, use a simple for ... inconditional loop wherecontaining a condition to increment 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

, , 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

NSCounted, @user28434 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")
+5

NSCountedSet.

, NSCountedSet, . NSCountedSet , . , NSSet, . , NSSet, ; , , . NSSet NSMutableSet , , .

While NSCountedSet and CFBag are not free bridges, they provide similar functionality. For more information on CFBag, see CFBag.

let countedSet = NSCountedSet(array: myArray)
let countOfA = countedSet.count(for: "a") // returns 4

Being a nonequivalent Objective-C object, it erases the type, so use it with caution.

+1
source

When solving such problems, I usually use it filterto create a new array with only "a" elements, and then just call it countinto a new array.

let count = myArray.filter({$0 == "a"}).count
print("The element 'a' occurs \(count) times")
0
source

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


All Articles