2016-12-25 77 views
0

复杂的字典(关联数组)调用过滤器我有此数组:在迅速

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

我与许多过滤器和地图constelations尝试过,但我总是得到这样的结构,结果是:

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

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

+0

首先,你的数组是字典,你为什么要这么做复杂,你不觉得,而不是使用属性键和值做类Filter,你需要使用第一个字符包含第一个字符后面的城市和第二个字符串数组,包含该对象的所有城市名称。 –

+0

相关:http://stackoverflow.com/questions/24116271/whats-the-cleanest-way-of-applying-map-to-a-dictionary-in-swift。 –

回答

1

也许你应该知道的一件事是map方法Dictionary返回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 
} 

(一般情况下,斯威夫特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>]] 
+3

一个for-in循环是可取的,因为它可以直接对结果字典进行变异,而使用reduce可以为每次迭代创建一个中间字典,使其以二次而不是线性时间运行。 – Hamish