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

问题描述 投票:1回答:2

当所有值不是同一类型时,我正在寻找一种优雅(功能)的方法来根据对值类型过滤字典。即从[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
}

但我对这种实施不满意......是吗?

swift dictionary swift4
2个回答
1
投票

我不是reduce的粉丝,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
投票

您可以使用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]
© www.soinside.com 2019 - 2024. All rights reserved.