【问题标题】:calling filter on complex dictionary (associative array) in swift快速调用复杂字典(关联数组)上的过滤器
【发布时间】:2017-05-10 04:16:18
【问题描述】:

我有这个数组:

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")]
]

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

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{$0.value != "augsburg"}]
})

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

【问题讨论】:

  • 首先你的数组是字典,你为什么要把它弄得这么复杂,你不觉得不是用属性键和值来制作类过滤器,你需要用第一个字符来制作它包含第一个较晚的城市和第二个字符串数组,其中包含该对象的所有城市名称。

标签: swift dictionary filter reduce


【解决方案1】:

也许你应该知道的一件事是Dictionarymap 方法返回Array,而不是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 {$0.value != "augsburg"}
    return mutableDict
}

(通常,Swift Dictionary 是关联数组的基于哈希表的实现,但您最好避免将 arry 命名为 Dictionary 变量。这样的命名非常混乱。)

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

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

【讨论】:

  • 最好使用 for-in 循环,因为它可以直接改变结果字典,而使用 reduce 会为每次迭代创建一个中间字典,使其以二次而不是线性时间运行。跨度>
猜你喜欢
  • 2018-09-22
  • 1970-01-01
  • 2015-10-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-09-11
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多