我有两个系列:
let collection1:[String:[String:NSObject]] = ["somekey":["nestedkey":"value"]]
let collection2:[String:[String:NSObject]] = ["somekey":["nestedkey":"value"]]
//I would like to compare them using the following:
let collectionsAreEqual = collection1 == collection2
将上述代码复制并粘贴到游乐场会出现以下错误:
我知道我可以为此写一个相同的功能:
infix func == (this:[String:[String:NSObject]], that:[String:[String:NSObject]]){
//return true or false
}
在目标c中,isEqual:在NSDictionary上处理这个没问题,因为它为你做了嵌套比较。是否有一些通常在swift中处理此问题的方法?
更新
我可以使用以下内容:
//:[String:[String:NSObject]]
let collection1:[String:NSObject] = ["somekey":["nestedkey":"value"]]
let collection2:[String:NSObject] = ["somekey":["nestedkey":"value"]]
//I would like to compare them using the following:
let collectionsAreEqual = collection1 == collection2
但它需要使用NSObject作为声明中的值。是否有一种纯粹的快速方法来处理这个问题?
答案 0 :(得分:14)
这是一个相等运算符,它将比较任何两个具有相同类型的嵌套字典:
func ==<T: Equatable, K1: Hashable, K2: Hashable>(lhs: [K1: [K2: T]], rhs: [K1: [K2: T]]) -> Bool {
if lhs.count != rhs.count { return false }
for (key, lhsub) in lhs {
if let rhsub = rhs[key] {
if lhsub != rhsub {
return false
}
} else {
return false
}
}
return true
}
答案 1 :(得分:0)
试试这个:
let collection1:[String:NSObject] = ["somekey":["nestedkey":"value"]]
let collection2:[String:NSObject] = ["somekey":["nestedkey":"value"]]
let collectionsAreEqual = ((collection1 as NSDictionary).isEqual(collection2 as NSDictionary)
通过将swift对象转换为Foundation对象,它们将获得相等运算符。他们会递归地调用每个元素上的相等运算符,所以你有深入的比较。