Search code examples
arraysswiftgenericsset-difference

Generic Array Extension for symmetricDifference


I wrote this function to get the difference between two arrays of strings.

func difference<T:Hashable>(array1: [T] ,array2:[T]) ->[T]? {
   let set1 = Set<T>(array1)
   let set2 = Set<T>(array2)
   let intersection = set1.symmetricDifference(set2)
   return Array(intersection)
}

Now I want to extend it to a generic function for different types like Int, Double etc...

extension  Array where Element: Hashable {
   func difference<T:Hashable>(array2: [T]) -> [T] {
      let set1 = Set(self)
      let set2 = Set(array2)
      let intersection = set1.symmetricDifference(set2)
      return Array(intersection)
  }
}

With this extension, I get the error:

Generic parameter 'S' could not be inferred.

I tried different approaches but in vain. What could be the problem?


Solution

  • It's exactly as @Hamish mentioned in his comment above, you're extending Array with one type and trying to execute the symmetricDifference with an another type (T: Hashable) that the compiler cannot infer.

    You can fix it returning an [Element] and use it the same type as argument in the function, something like this:

    extension Array where Element: Hashable {
    
       func difference(array2: [Element]) -> [Element] {
          let set1 = Set(self)
          let set2 = Set(array2)
          let intersection = set1.symmetricDifference(set2)
          return Array(intersection)
       }
    }
    

    I hope this help you.