Home > Software engineering >  How to get count of NSCountedSet?
How to get count of NSCountedSet?

Time:10-23

I'm trying to get count of values from NSCountedSet using loop and have no idea how to get these.

for item in set {

}

I'll be grateful for any help!

CodePudding user response:

You would call count(for:) on the set:

import Foundation

let set: NSCountedSet = ["a", "b", "b", "c", "c", "c"]

for item in set {
    print("\(set.count(for: item)) x \"\(item)\"")
}

Prints:

1 x "a"
2 x "b"
3 x "c"

CodePudding user response:

Use method count(for:)

let mySet = NSCountedSet()
mySet.add(1)
mySet.add(2)
mySet.add(2)

for value in mySet {
    let count = mySet.count(for: value)
    print("Count for \(value) is \(count)")
}

However, note that NSCountedSet is untyped (it's an old Objective-C class), therefore it is not very well suited for Swift.

Luckily, we can implement the same using a simple [T: Int] dictionary.

For example:

struct MyCountedSet<T: Hashable>: Sequence {
    typealias Element = T
    
    private var counts: [T: Int] = [:]

    mutating func add(_ value: T) {
        counts[value, default: 0]  = 1
    }

    func count(for value: T) -> Int {
        return counts[value, default: 0]
    }

    func makeIterator() -> AnyIterator<T> {
        return AnyIterator<T>(counts.keys.makeIterator())
    }
}

var myCountedSet = MyCountedSet<Int>()
myCountedSet.add(1)
myCountedSet.add(2)
myCountedSet.add(2)

for value in myCountedSet {
    let count = myCountedSet.count(for: value)
    print("Count for \(value) is \(count)")
}
  • Related