使命:我需要提供一个Array扩展方法,它可以比较原始类型符合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, $0)}) {
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)
}
}
如何限制数组的扩展&#34;元素&#34;使用Equatable类型的RawValue作为RawRepresentable的typealias?
或者,使这种比较成为可能的另一种方法是什么?
答案 0 :(得分:2)
扩展名的约束用逗号分隔,而不是
按&
。 containsTheSameElements
必须采用[T]
参数
其中T
是RawRepresentable
,RawValue
为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 { $0.rawValue != $1.rawValue }
}
}
作为数组元素。
示例:
extension Array where Element: RawRepresentable, Element.RawValue: Equatable {
func containsTheSameElements(as array: [Element]) -> Bool
{
return self.count == array.count &&
!zip(self, array).contains { $0.rawValue != $1.rawValue }
}
}
更新:如果只需要数组,则更简单 相同类型:
extension Array where Element: RawRepresentable, Element.RawValue: Equatable {
func containsTheSameElements(as array: [Element]) -> Bool
{
return containsTheSameElements(as: array, condition: enumComparisonClosure)
}
}
或者,重复使用现有方法:
For Each vbCom In .VBComponents