我有2个词典: let foo: [String: Any] = ["name": "John", "isHuman": true, "age": 20]let bar: [String: Any] = ["name": "Ann", "isHuman": true, "age": 34] 我想在比较中排除某些键时进行比较.我要排除的键位于另一个字
let foo: [String: Any] = ["name": "John", "isHuman": true, "age": 20] let bar: [String: Any] = ["name": "Ann", "isHuman": true, "age": 34]
我想在比较中排除某些键时进行比较.我要排除的键位于另一个字典中:
let car: [String: Any] = ["age": 20]
我有这个扩展名:
extension Dictionary where Key: Equatable { func isEqualTo(_ dictionary: Dictionary, excluding: [Key] = []) -> Bool { let left = filter({ !excluding.contains($0.key) }) let right = dictionary.filter({ !excluding.contains($0.key) }) return NSDictionary(dictionary: left).isEqual(to: right) } }
但是当我调用它时,我需要将排除的键包装在Array中,否则编译器将失败:
Cannot convert value of type ‘Dictionary.Keys’ to expected argument type ‘[String]’
foo.isEqualTo(bar,不包括:Array(car.keys))有效.
foo.isEqualTo(bar,不包括:car.keys)导致编译器错误.
我可以调整扩展程序,以避免将排除的键包装在数组中吗?
car.keys的类型为Dictionary< Key,Value> .Keys,它是一个集合而不是数组.
如果将函数声明为
func isEqualTo<C: Collection>(_ dictionary: Dictionary, excluding: C) -> Bool where C.Element == Key
然后两个
foo.isEqualTo(bar, excluding: Array(car.keys)) foo.isEqualTo(bar, excluding: car.keys)
编译和工作.