user2640633
user2640633

Reputation:

Get each unique element in array and keep count for tableview swift

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

Upvotes: 1

Views: 970

Answers (1)

vadian
vadian

Reputation: 285260

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))

Upvotes: 4

Related Questions