泛型 – 对泛型扩展的快速类型约束

前端之家收集整理的这篇文章主要介绍了泛型 – 对泛型扩展的快速类型约束前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
经过一些压力后,我创建了以下通用函数

  1. func removeDupes<T : Hashable > (inout inputCollection : [T] ) -> [T] {
  2. var hashMap = [T : Bool]()
  3. var output = 0
  4. for thing in inputCollection {
  5. if !hashMap[thing] {
  6. hashMap[thing] = true
  7. inputCollection[output++] = thing
  8. }
  9. }
  10. while (inputCollection.count > output) {
  11. inputCollection.removeLast()
  12. }
  13. return inputCollection
  14. }

所以当你这样做时:

  1. var names = ["Bob","Carol","Bob","Ted","Alice","Alice"]
  2. removeDupes(&names)

名称将包含:[“Bob”,“Carol”,“Ted”,“Alice”]

现在我想在Array上添加“removeDupes”作为扩展方法,我正在用语法进行挣扎,因为我必须将它限制为Hashable项的数组.

我希望我可以这样声明:

  1. extension Array {
  2. func removeDupes< T : Hashable> () -> [T] {
  3. return removeDupes(&self)
  4. }
  5. }

但我得到错误

数组不能转换为’@lvalue inout $T5′

我怀疑答案是“你这个白痴,做这个……”还是“你做不到”

它会是哪个?

猜你在找的Swift相关文章