如何从字典中删除指定键的一对?

时间:2019-07-16 08:37:57

标签: ios swift

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

我创建了一个函数filterAndExtract()。但是,它只会迭代并且不执行任何操作。在每种情况下比较(布尔)参数和键时,它均无法按预期工作。我想知道如何识别一对钥匙,因此我可以处理集合中的箱子。预先感谢!

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--------------------------------------------------

2 个答案:

答案 0 :(得分:2)

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

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

collections

答案 1 :(得分:1)

首先,如果将remove函数封装到Example {

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

    mutating func remove(key: Tags) -> String? {
        return pair.removeValue(forKey: key)
    }
}

第二,您可以使用map执行以下任务:

func filterAndExtract(collection: [Example], tag: Tags) -> [Example] {
    return collection.map { item -> Example in
        var edited = item
        edited.remove(key: tag)
        print("\(edited.title) and \(edited.pair.values) \nNEXT TURN--------------------------------------------------\n")
        return edited
    }
}

我在两个函数中都返回了一些值,因此您可以根据需要使用它们。