我有 2 组字典。我想写一个比较这两个数组的函数。仅当主数组包含子数组元素时,函数才应返回true 。否则它应该返回false。
这是我的逻辑-
let mainArry = [ ["id":"1","products":["pid": 1, "name": "A", "price": "$5"]], ["id":"3","products":["pid": 3, "name": "B", "price": "$1"]], ["id":"2","products":["pid": 14, "name": "C", "price": "$15"]]]
let array1 = [ ["id":"1","products":["pid": 1, "name": "A", "price": "$5"]], ["id":"3","products":["pid": 3, "name": "B", "price": "$1"]]]
let array2 = [ ["id":"1","products":["pid": 1, "name": "A", "price": "$5"]], ["id":"3","products":["pid": 4, "name": "B", "price": "$1"]]]
func compareDictionary(mainArry:[[String: Any]], arr2: [[String: Any]])-> Bool{
let itemsId = arr2.map { $0["id"]! } // 1, 3, 14
let filterPredicate = NSPredicate(format: "id IN %@", itemsId)
let filteredArray = mainArry.filter{filterPredicate.evaluate(with:$0) }
if filteredArray.count != arr2.count {
return false
}
for obj in filteredArray {
let prd = obj as Dictionary<String, Any>
let str = prd["id"] as! String
let searchPredicate = NSPredicate(format: "id == %@", str )
let filteredArr = arr2.filter{searchPredicate.evaluate(with:$0) }
if filteredArr.isEmpty {
return false
}
if !NSDictionary(dictionary: obj["products"] as! Dictionary<String, Any>).isEqual(to: filteredArr.last!["products"] as! [String : Any]) {
return false
}
}
return true
}
let result1 = compareDictionary(mainArry: mainArry, arr2: array1)
let result2 = compareDictionary(mainArry: mainArry, arr2: array2)
print("Result1 = \(result1)") // true
print("Result2 = \(result2)") //false
这是工作。但我想知道实现这一目标的最佳方法。
而不是使用for循环进行比较。我想使用这样的过滤器
let arrayC = filteredArray.filter{
let dict = $0
return !arr2.contains{ dict == $0 }
}
如果 arrayC 为空,则表示两个数组相等。