Home > Back-end >  Collection Extension for checking unique values for a given property in Swift
Collection Extension for checking unique values for a given property in Swift

Time:07-07

I have an extension for a Collection that checks if the items inside the collection has a unique value for a specific property and I have implemented it like this:

func isPropertyUnique <T: Hashable> (by: ((Element) -> (T))) -> Bool {
    var set = Set<T>()
    for value in self {
      set.insert(by(value))
    }
    return set.count > 1
  }

To use it, one would just call

items.isPropertyUnique { $0.propertyName }

Anyone else have any idea for a better implementation? Mine feels a bit hackish because I use a set to check for uniqueness.

How do I implement this logic without using Set?

CodePudding user response:

A bit simplified (because Collection already knows own element type and enough only key path) and faster (because it is not needed to iterate all as soon as first non-unique found)

Here is a result

func isUnique<T: Hashable>(by key: KeyPath<Element, T>) -> Bool {
    var set = Set<T>()
    for value in self {
        set.insert(value[keyPath: key])
        if set.count > 1 { return false }
    }
    return true
}

and usage

items.isUnique(by: \.propertyName)

Tested with Xcode 13.4

  • Related