1

I am trying to iterate over an array and find all the duplicates. I want to populate my TableView with ONE of each of the unique items in the array, and be able to use a segmented controller to sort by the name of the item OR the count of the item...

I want the cell to have labelOne = unique array object, and labelTwo = how many times that object is repeated.

For example

var exampleArr = ["apple", "apple", "apple", "apple", "cat", "cat", "laptop"]

I want to be able to say apple: 4, cat: 2, laptop: 1

I found this answer...

My concern is that these answers (from hyperlink) return dictionaries.

Is it possible to create a sortable table view using a dictionary? Or is there a better way to do this

RubberDucky4444
  • 2,330
  • 5
  • 38
  • 70
  • In the linked question there's an answer suggesting `NSCountedSet`. That is a possible solution. – vadian Jun 14 '17 at 06:25

1 Answers1

5

NSCountedSet can do what you are looking for (requires Foundation)

let exampleArr = ["apple", "apple", "apple", "apple", "cat", "cat", "laptop"]
let countedSet = NSCountedSet(array: exampleArr)
for item in countedSet {
    print(item, countedSet.count(for: item))
}

To use the set in a table view create an array from the unique objects

var dataArray = [String]()

dataArray = countedSet.allObjects as! [String]

You can even sort the array

dataArray.sort()

In cellForRow get the item from dataArray and the occurrences from countedSet

let item = dataArray[indexPath.row]
let occurrences = countedSet.count(for: item)

Note:

NSCountedSet has no idea about the type of the containing items, so if you need the type you have to cast it:

print(item as! String, countedSet.count(for: item))
vadian
  • 274,689
  • 30
  • 353
  • 361
  • Thank you for the help. I have never used NSCountedSet. In the TableView numberOfRowsInSection I am trying to use countedSet.count but it seems to want count(for:) similar to what you described above. How can I return the Int that the method wants? – RubberDucky4444 Jun 14 '17 at 07:09