0

How to count a number of time in array there are "Yes" ? In swift

["julien: Yes","elie: Yes", "Mark: No", "Jean: Yes"]

For exemple here there are 3 times Thanks ;)

5
  • What did you try and what went wrong ? Commented Dec 14, 2015 at 12:15
  • 3
    What have you tried so far? However, I do not think that this is some smart data structure. Commented Dec 14, 2015 at 12:17
  • 1
    Possible duplicate of How to count occurrences of an element in a Swift array? Commented Dec 14, 2015 at 12:21
  • This can be done very simple with enumeration. Or do you want to do this in some smart functional-style way? Commented Dec 14, 2015 at 12:24
  • 1
    Possible duplicate of Count number of items in an array with a specific property value Commented Mar 7, 2017 at 20:41

4 Answers 4

4

How about something like this?

//: Playground - noun: a place where people can play

import UIKit

let array = ["julien: Yes","elie: Yes", "Mark: No", "Jean: Yes"]
let results = array.map({ $0.lowercaseString.containsString("yes") })
let count = results.filter({ $0 == true }).count
count // 3

You can also make it a one liner:

let count = array.filter({ $0.lowercaseString.containsString("yes") }).count 

Note: I also added a check for case sensitivity just incase the data source was inconsistent

Sign up to request clarification or add additional context in comments.

Comments

2
let a = ["julien: Yes","elie: Yes", "Mark: No", "Jean: Yes"]
let filtered = a.filter { (str) -> Bool in
    return str.containsString("Yes")
}
print(filtered.count)

Comments

2
let array = ["julien: Yes","elie: Yes", "Mark: No", "Jean: Yes"]
let count = array.reduce(0) { $0 + ($1.containsString("Yes") ? 1 : 0) }
count // 3

Comments

1

You can use NSPredicate to get required output like below

var arrayTemp = NSMutableArray(objects: "julien: Yes","elie: YES", "elie: NO", "Jean: Yes")
var predicate = NSPredicate(format: "self contains[cd] %@", "Yes")
arrayTemp.filterUsingPredicate(predicate)
print("COUNT===\(arrayTemp.count)")// 3 

Comments

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.