比较包含实际上相等类型的字典,基于非等同数据结构

时间:2016-01-10 11:02:13

标签: swift generics dictionary comparison equality

所以我想把两个相同类型的词典等同起来AnyLanguage Hashable符合Equatable,因此也符合SortedList,所以这不是问题。另一方面,Equatable不符合Element,因为它在public struct SortedList<Element> { ... } 上是通用的,没有任何限制:

SortedList

现在,当Elements符合Equatable时,我已为public func ==<T: Equatable>(left: SortedList<T>, right: SortedList<T>) -> Bool 实现了等于运算符:

let dictA: [AnyLanguage: SortedList<String>] = [:]
let dictB: [AnyLanguage: SortedList<String>] = [:]

dictA == dictB

现在,在比较上述两个词典时:

SortedList

我收到以下错误:

Error

我假设编译器抱怨,因为Equatable不符合Element,即使我已经为equatable SortedList<String>实现了比较运算符(String会能够使用,因为#!/usr/bin/env python """ Get information about images in a folder. """ from os import listdir from os.path import isfile, join from PIL import Image def print_data(data): """ Parameters ---------- data : dict """ for k, v in data.items(): print("%s:\t%s" % (k, v)) print("Min width: %i" % data['min_width']) print("Max width: %i" % data['max_width']) print("Min height: %i" % data['min_height']) print("Max height: %i" % data['max_height']) def main(path): """ Parameters ---------- path : str Path where to look for image files. """ onlyfiles = [f for f in listdir(path) if isfile(join(path, f))] # Filter files by extension onlyfiles = [f for f in onlyfiles if f.endswith('.jpg')] data = {} data['images_count'] = len(onlyfiles) data['min_width'] = 10**100 # No image will be bigger than that data['max_width'] = 0 data['min_height'] = 10**100 # No image will be bigger than that data['max_height'] = 0 for filename in onlyfiles: im = Image.open(filename) width, height = im.size data['min_width'] = min(width, data['min_width']) data['max_width'] = max(width, data['max_height']) data['min_height'] = min(height, data['min_height']) data['max_height'] = max(height, data['max_height']) print_data(data) if __name__ == '__main__': main(path='.') 是等同的。)

如何比较两个词典?

2 个答案:

答案 0 :(得分:2)

词典的==运算符需要Key和Value 类型符合Equatable

您已为==实施了(受限制的)SortedList<Element>运算符。 但是为类型实现==运算符不会生成该类型 自动Equatable。必须明确声明一致性。

不幸的是,(目前)只有<{em> SortedList<Element>才能使Equatable符合Element Equatable。对于数组存在同样的问题,比较 Why can't I make Array conform to Equatable?进行讨论 在Apple开发者论坛中。

据我所知,唯一的解决方案是制作SortedList<Element> 无条件地符合Equatable(如Cristik's answer),或定义 字典的自定义比较运算符

func ==<Key : Equatable, T : Equatable>(lhs: [Key : SortedList<T>], rhs: [Key : SortedList<T>]) -> Bool {
    // ...
}

答案 1 :(得分:0)

SortedList不是Equatable,因此Dictionary无法比较这些元素。您需要声明为Equatable,并在没有通用约束的情况下实现==。这将有效:

public struct SortedList<Element>: Equatable { ... }

public func ==<T>(left: SortedList<T>, right: SortedList<T>) -> Bool

如果您想限制SortedListEquatable个元素,可以声明它只接受符合Equatable的内容

public struct SortedList<Element: Equatable>: Equatable

但是对于SortedList我认为Comparable更适合。