你如何在其值类型上过滤快速字典?

时间:2017-12-22 15:51:16

标签: swift dictionary swift4

我正在寻找一种优雅(功能)的方法,当所有值不是同一类型时,根据配对值类型过滤字典。即从[AnyHashable : Any][AnyHashable : T]的方式?

使用flatMap为您提供了一系列可以减少的元组:

var result = dictionary.flatMap({ pair in
    pair as? (AnyHashable, T)
}).reduce([AnyHashable : T]()) { dict, tuple in
    var dict = dict
    dict[tuple.0] = tuple.1
    return dict
}

但是我对这个实现不满意......是吗?

2 个答案:

答案 0 :(得分:1)

我不是Dictionary(uniqueKeysWithValues:)的粉丝,let dict: [AnyHashable: Any] = [ 1: 1, 2: "foo", "3": 3, 4: 5.0, true: "17" ] func filterByType<T>(_ dict: [AnyHashable: Any]) -> [AnyHashable: T] { return Dictionary(uniqueKeysWithValues: dict.flatMap { ($0,$1) as? (AnyHashable, T) }) } let strValues: [AnyHashable: String] = filterByType(dict) 似乎更适合:

{{1}}

答案 1 :(得分:1)

你可以使用Swift 4 reduce(into:)方法,其部分结果已经是可变的:

extension Dictionary {
    func flatMapValues<T>(into type: T.Type) -> [Key: T] {
        return reduce(into: [:]) { $0[$1.key] = $1.value as? T }
    }
}
let dict: [AnyHashable: Any] = ["key1": 1, "key2": 2, 3: "Three", Date(): "Just a String", "key5": 5]

let integersDictionary = dict.flatMapValues(into: Int.self) // ["key2": 2, "key5": 5, "key1": 1]