Class 扩展类型别名的 属性 类型约束

Class extension typealias's property type constraint

任务:我需要提供一个数组扩展方法,该方法将比较原始类型符合 Equatable 的 2 个原始可表示数组,并通过重用以下代码判断数组是否包含相同的元素。

我目前拥有的:

public extension Array {
  func containsTheSameElements(as array: [Element], condition: @escaping (Element, Element) -> Bool) -> Bool {
    var localCopy = array

    let countOfUncommonElements = reduce(0) { (uncommonElementsCount: Int, item: Element) -> Int in
      if let index = localCopy.index(where: {condition(item, [=12=])}) {
        localCopy.remove(at: index)
        return uncommonElementsCount
      } else {
        return uncommonElementsCount + 1
      }
    }

    return countOfUncommonElements == 0 && count == array.count
  }
}

func enumComparisonClosure<T: RawRepresentable>(firstItem: T, secondItem: T) -> Bool where T.RawValue: Equatable {
  return firstItem == secondItem
}

我目前的使用情况:

class Somewhere {
  enum EnumType: String {
    case first
    case second
  }

  func method() {
    let firstArray: [EnumType] = [.first, .second]
    let secondArray: [EnumType] = [.second]

    firstArray.containsTheSameElements(as: secondArray, condition: enumComparisonClosure)
  }
}

我想如何使用它:

firstArray.containsTheSameElements(as: secondArray)

我希望如何实现它:

public extension Array {
  func containsTheSameElements<Element: RawRepresentable>(as array: [Element]) -> Bool where Element.RawValue: Equatable {
    return containsTheSameElements(as: array, condition: enumComparisonClosure)
  }
}

如何将数组的扩展名 "Element" typealias 限制为具有 Equatable 类型的 RawValue 的 RawRepresentable?

或者使这种比较成为可能的另一种方法是什么?

扩展名的约束用逗号隔开,不是 通过 &containsTheSameElements 必须采用 [T] 参数 其中 T 是具有相同 RawValueRawRepresentable 作为数组元素。

示例:

extension Array where Element: RawRepresentable, Element.RawValue: Equatable {

    func containsTheSameElements<T>(as array: [T]) -> Bool
    where T: RawRepresentable, T.RawValue == Element.RawValue
    {
        return self.count == array.count &&
            !zip(self, array).contains { [=10=].rawValue != .rawValue }
    }
}

更新:如果你只需要数组的话会更简单 同类型:

extension Array where Element: RawRepresentable, Element.RawValue: Equatable {

    func containsTheSameElements(as array: [Element]) -> Bool
    {
        return self.count == array.count &&
            !zip(self, array).contains { [=11=].rawValue != .rawValue }
    }
}

或者,重复使用您现有的方法:

extension Array where Element: RawRepresentable, Element.RawValue: Equatable {

    func containsTheSameElements(as array: [Element]) -> Bool
    {
        return containsTheSameElements(as: array, condition: enumComparisonClosure)
    }
}