swiftnscountedset

Object count in NSCountedSet using property


This is a followup to this post from Paul Hudson: https://www.hackingwithswift.com/example-code/arrays/how-to-count-objects-in-a-set-using-nscountedset

I changed it as follows to use a Person struct:

struct Person {
    var name: String
    
    init(name: String) {
        self.name = name
    }
}

var array: [Person] = []

array.append(Person(name: "Bob"))
array.append(Person(name: "Charlotte"))
array.append(Person(name: "John"))
array.append(Person(name: "Bob"))
array.append(Person(name: "James"))
array.append(Person(name: "Sophie"))
array.append(Person(name: "Bob"))

let set = NSCountedSet(array: array)

What is the equivalent of print(set.count(for: "Bob")) to get the count of all persons with the name "Bob" ?

UPDATE: I was too fast with copy/paste the code from the link above, code is updated.

In my case I first create an array, and then the counted set. UBut the question remains the same.


Solution

  • You cannot ask for apples (String) but there are oranges (Person).

    To get the number of occurrences of people named Bob by taking advantage of the NSCountedSet functionality you have to adopt Hashable

    struct Person : Hashable {
        let name: String
    }
    

    and then ask for a Person

    print(set.count(for: Person(name: "Bob")))