11

How do you count the amount of unique items in an Array?

Example:

let array:Array<Int> = [1,3,2,4,6,1,3,2]

Count function: array.count will give 8

but I want to count unique items and this will give 5

6 Answers 6

16

As of Swift 1.2, Swift has a native Set type. Use the Set constructor to create a set from your array, and then the count property will tell you how many unique items you have:

let array = [1,3,2,4,6,1,3,2]

let set = Set(array)
print(set.count)  // prints "5"

For Swift 1.1 and earlier:

Turn your array into an NSSet:

let array = [1,3,2,4,6,1,3,2]

let set = NSSet(array: array)
println(set.count)  // prints "5"

You can read more about it here.


If you are interested in how many of each item you have, you can use a dictionary to count the items:

var counts = [Int:Int]()

for item in array {
    counts[item] = (counts[item] ?? 0) + 1
}

print(counts)        // prints "[6: 1, 2: 2, 3: 2, 1: 2, 4: 1]"
print(counts.count)  // prints "5"
print("There are \(counts[1] ?? 0) ones.")    // prints "There are 2 ones."
print("There are \(counts[7] ?? 0) sevens.")  // prints "There are 0 sevens."
Sign up to request clarification or add additional context in comments.

Comments

8

You can use NSSet to throw away duplicates:

let array:Array<Int> = [1,3,2,4,6,1,3,2]
let count = NSSet(array: array).count
println(count)

This prints:

5

Comments

5

implement the function countDistinct(numbers: [Int]) to return the number of distinct elements in the array. NSSet documentation for Swift https://developer.apple.com/documentation/foundation/nsset

func countDistinct(numbers: [Int]) -> Int {
    let array:Array<Int> = numbers
    let count = NSSet(array: array).count
    return count
}

print(countDistinct(numbers: [20, 10, 10, 30, 20]))

Comments

1

If you prefer to stick with pure swift, a possible solution consists of:

  1. sorting the array
  2. traversing the and count the number of times an element differs from the previous one

Translated in code:

let start: (Int, Int?) = (0, nil)
let count = array.sorted(<).reduce(start) { initial, value in
    (initial.0 + (initial.1 == value ? 0 : 1), value)
}

let uniqueElements = count.0

the result is stored in the element 0 of the count tuple.

Explanation: the start tuple is initialized with 0 and nil, and passed as the initial value to the reduce method, called on a sorted copy of the array. At each iteration, a new tuple is returned, containing the current array element and the current counter, increased by one if the current element is different than the previous one.

Comments

1

You can also use following generic method for counting unique values inside an array.

func countUniques<T: Comparable>(_ array: Array<T>) -> Int {
    let sorted = array.sorted()
    let initial: (T?, Int) = (.none, 0)
    let reduced = sorted.reduce(initial) {
        ($1, $0.0 == $1 ? $0.1 : $0.1 + 1)
    }
    return reduced.1
}

Comments

1
let numbersInArray = [1, 2, 3, 4, 5, 1, 2, 3]
let uniqueNumbers = Array(Set(numbersInArray))
print(uniqueNumbers.count)

2 Comments

Thank you for contributing to the Stack Overflow community. This may be a correct answer, but it’d be really useful to provide additional explanation of your code so developers can understand your reasoning. This is especially useful for new developers who aren’t as familiar with the syntax or struggling to understand the concepts. Would you kindly edit your answer to include additional details for the benefit of the community?
This is a great answer. Use Set() to ensure that each element only appears once in the collection, then put that result into a new array and simply count it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.