Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/swift/18.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Arrays 对称性差异的通用数组扩展_Arrays_Swift_Generics_Set Difference - Fatal编程技术网

Arrays 对称性差异的通用数组扩展

Arrays 对称性差异的通用数组扩展,arrays,swift,generics,set-difference,Arrays,Swift,Generics,Set Difference,我编写这个函数是为了得到两个字符串数组之间的差异 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) }

我编写这个函数是为了得到两个字符串数组之间的差异

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)
}
通过此扩展,我得到了错误:

Generic parameter 'S' could not be inferred.
我尝试了不同的方法,但没有成功。
可能是什么问题?

正如@Hamish在上面的评论中所提到的,您正在用一种类型扩展
数组
,并试图用编译器无法推断的另一种类型(
T:Hashable
)执行
symmetricDifference

您可以修复它,返回一个
[Element]
,并在函数中使用与参数相同的类型,如下所示:

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

我希望这对您有所帮助。

您正在为您的方法定义一个新的通用占位符
T
,它不一定与
元素的类型相同。只需使用一个参数并返回类型
[Element]
——请参见示例。
func-symmetricDifference(to-array:[Element])->[Element]{
func-symmetricDifference(to-array:array)->array{
我认为最好返回一个集合而不是数组:
扩展数组,其中Element:Hashable{func-symmetricDifference(to-array:array)->Set{return Set(self).symmetricDifference(array)}
您也可以使用
array
而不是
[Element]
扩展数组,其中Element:Hashable{func-symmetricDifference(to-array:array)->array{return return array(Set(self).symmetricDifference(array))}
无需设置第二个数组感谢所有的答案和解释。我想关于泛型我还有很多要学习的!
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)
   }
}