在 swift 中对复杂字典(关联数组)调用过滤器

calling filter on complex dictionary (associative array) in swift

我有这个数组:

class Filter {

    var key = ""
    var value = ""

    init(key: String, value: String) {
        self.key = key
        self.value = value
    }

}

let arry = [
    "a":[Filter(key:"city",value:"aachen"),Filter(key:"city",value:"augsburg")],
    "b":[Filter(key:"city",value:"bremen"),Filter(key:"city",value:"berlin")]
]

我想查找 augsburg 并使用过滤功能将其从字典中删除,因此输出如下所示:

let arry = [
    "a":[Filter(key:"city",value:"aachen")],
    "b":[Filter(key:"city",value:"bremen"),Filter(key:"city",value:"berlin")]
]

我尝试了很多过滤器和地图星座,但结果总是得到这个结构:

let arry = [
    ["a":[Filter(key:"city",value:"aachen")]],
    ["b":[Filter(key:"city",value:"bremen"),Filter(key:"city",value:"berlin")]]
]

例如使用此过滤器:

arry.map({ key,values in

    return [key:values.filter{[=14=].value != "augsburg"}]
})

这里有什么问题?如何过滤和映射更复杂的对象?

也许您应该知道的一件事是 Dictionary returns Arraymap 方法,而不是 Dictionary.

public func map<T>(_ transform: (Key, Value) throws -> T) rethrows -> [T]

因此,如果您希望筛选结果为 Dictionary,您可能需要使用 reduce:

class Filter: CustomStringConvertible {

    var key = ""
    var value = ""

    init(key: String, value: String) {
        self.key = key
        self.value = value
    }

    //For debugging
    var description: String {
        return "<Filter: key=\(key), value=\(value)>"
    }
}

let dict = [
    "a":[Filter(key:"city",value:"aachen"),Filter(key:"city",value:"augsburg")],
    "b":[Filter(key:"city",value:"bremen"),Filter(key:"city",value:"berlin")]
]

let filteredDict = dict.reduce([:]) {tempDict, nextPair in
    var mutableDict = tempDict
    mutableDict[nextPair.key] = nextPair.value.filter {[=11=].value != "augsburg"}
    return mutableDict
}

(一般来说,Swift Dictionary 是基于哈希-table 的关联数组实现,但你最好避免将 arry 命名为 Dictionary变量。这样的命名太混乱了。)

或者简单地使用 for-in 循环:

var resultDict: [String: [Filter]] = [:]
for (key, value) in dict {
    resultDict[key] = value.filter {[=12=].value != "augsburg"}
}
print(resultDict) //->["b": [<Filter: key=city, value=bremen>, <Filter: key=city, value=berlin>], "a": [<Filter: key=city, value=aachen>]]