首页 > 解决方案 > 如何从字典中删除指定键的一对?

问题描述

我想写一个带参数的函数,用于与字典的键进行比较。该函数迭代一个集合并检查 case 是否具有与此键的对。如果有,我想删除那对,将另一对留在这种情况下,然后继续下一个情况。

我创建了一个函数 filterAndExtract()。然而它只是迭代并且什么都不做。在每种情况下比较(Bool)参数和键时,它不能按预期工作。我想知道如何识别一对中的密钥,以便我可以对集合中的案例做一些事情。提前致谢!

enum Tags: String {
     case one = "One"
     case two = "Two"
     case three = "Three"
}

struct Example {
     var title: String
     var pair: [Tags: String]
}

let cases = [
     Example(title: "Random example One", pair: [Tags.one: "First preview", Tags.two: "Second preview"]),
     Example(title: "Random example Two", pair: [Tags.two: "Thrid preview", Tags.three: "Forth preview"]),
     Example(title: "Random example Three", pair: [Tags.three: "Fifth preview", Tags.one: "Sixth preview"])
]

func filterAndExtract(collection: [Example], tag: Tags) {
    for var item in collection {
        let keys = item.pair.keys

        for key in keys {
            if key == tag {
                item.pair.removeValue(forKey: key)
            }
        }
    }

    for i in collection {
        print("\(i.title) and \(i.pair.values) \nNEXT TURN--------------------------------------------------\n")
    }
}

//Results:

//Random example One and ["Second preview", "First preview"] 
//NEXT TURN--------------------------------------------------

//Random example Two and ["Thrid preview", "Forth preview"] 
//NEXT TURN--------------------------------------------------

//Random example Three and ["Fifth preview", "Sixth preview"] 
//NEXT TURN--------------------------------------------------

//Solution (how I want it to look at the end):
for var i in cases {
    i.pair.removeValue(forKey: .three)
    print("\(i.title) and \(i.pair.values) \nNEXT TURN--------------------------------------------------\n")
}
//Random example One and ["Second preview", "First preview"] 
//NEXT TURN--------------------------------------------------

//Random example Two and ["Thrid preview"] 
//NEXT TURN--------------------------------------------------

//Random example Three and ["Sixth preview"] 
//NEXT TURN--------------------------------------------------

标签: iosswift

解决方案


Swift 集合是值类型。每当您将集合分配给变量时,您都会获得该对象的副本。

要修改参数collections,您必须使其可变,并且必须直接在内部修改值collections

func filterAndExtract(collection: [Example], tag: Tags) {
    var collection = collection
    for (index, item) in collection.enumerated() {
        let keys = item.pair.keys

        for key in keys {
            if key == tag {
                collection[index].pair.removeValue(forKey: key)
            }
        }
    }

    for i in collection {
        print("\(i.title) and \(i.pair.values) \nNEXT TURN--------------------------------------------------\n")
    }
}

推荐阅读