2016-12-25 219 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