Swift version: 5.6
One of my favorite little gems in Cocoa Touch is called NSCountedSet
, and it's the most efficient way to count objects in a set. Here's the code:
let set = NSCountedSet()
set.add("Bob")
set.add("Charlotte")
set.add("John")
set.add("Bob")
set.add("James")
set.add("Sophie")
set.add("Bob")
print(set.count(for: "Bob"))
Now to how it works: a set is like an array, except each item can appear only once. If we used an array in the above code, it would contain seven objects: three Bobs, one Charlotte, one John, one James and one Sophie. If we used a Swift set in the above code, it would contain four objects: one Bob, one Charlotte, one John, one James and one Sophie – the set ensures each item appears only once.
Now for the twist: NSCountedSet
works similar to a set insofar as each object can appear only once, but it keeps track of how many times each item was added and removed. So, our counted set will have four objects in (like it would if it were a regular set), but NSCountedSet
has a count(for:)
method that will report back that Bob was added three times.
SPONSORED Still waiting on your CI build? Speed it up ~3x with Blaze - change one line, pay less, keep your existing GitHub workflows. First 25 HWS readers to use code HACKING at checkout get 50% off the first year. Try it now for free!
Sponsor Hacking with Swift and reach the world's largest Swift community!
Available from iOS 2.0
This is part of the Swift Knowledge Base, a free, searchable collection of solutions for common iOS questions.
Link copied to your pasteboard.