ios 根据特定键、值对获取唯一记录的列表

jvlzgdj9  于 2023-01-27  发布在  iOS
关注(0)|答案(1)|浏览(187)

我是swift的新手,我想知道我是否可以根据2个数组中的键,值对获得唯一的值。
阵列-1:

let arr1 = [
   ["title" : "News", "icon" : "news_1"],
   ["title" : "Food", "icon" : "food_1"]
]

阵列-2:

let arr2 = [
   ["title" : "News", "icon" : "news_2"],
   ["title" : "Technology", "icon" : "tech_1"]
]

如何得到这样的结果
阵列-3:

let arr3 = [
   ["title" : "Food", "icon" : "food_1"],
   ["title" : "Technology", "icon" : "tech_1"]
]

因此,我需要数组1和数组2中所有唯一值的集合,这些值基于结果数组中名为“title”的键。
注意:这里我在数组1和2中有标题“food”,但是图标不同。

yc0p9oo0

yc0p9oo01#

你所寻找的可能是这两个数组的symmetric difference,但是正如评论中所指出的,你的数据结构并不适合这样做,如果你真的想坚持当前的结构,下面这个可能对你有用:

func symmetricDifference(arrays: [[[String: String]]], by key: String) -> [[String: String]] {
    var result = [String: [String: String]?]()
    for array in arrays {
        for element in array {
            guard let keyValue = element[key] else {
                // Ignore elements that do not contain the key, adjust as needed
                continue
            }
            
            // Check if we already saw the value
            if !result.keys.contains(keyValue) {
                // Add the element
                result[keyValue] = element
            } else {
                // We saw this keyValue already, remove the element
                result.updateValue(nil, forKey: keyValue)
            }
        }
    }
    
    // Only return elements where value is not nil
    return result.values.compactMap { $0 }
}

// Usage
symmetricDifference(arrays: [arr1, arr2], by: "title")

通过使用更合适的数据结构,您可以轻松地使用内置的Set运算符:

struct Category: Hashable {
    let title: String
    let icon: String
    
    func hash(into hasher: inout Hasher) {
        hasher.combine(title)
    }
    
    static func ==(lhs: Category, rhs: Category) -> Bool {
        lhs.title == rhs.title
    }
}

let set1 = Set([Category(title: "News", icon: "news_1"), Category(title: "Food", icon: "food_1")])
let set2 = Set([Category(title: "News", icon: "news_2"), Category(title: "Technology", icon: "tech_1"), Category(title: "News", icon: "news_2")])
let result = set1.symmetricDifference(set2)

相关问题