假设我有以下Swift字典:
var studioAlbums = ["Led Zeppelin":1969, "Led Zeppelin II": 1969, "Led Zeppelin III": 1970, "Led Zeppelin IV": 1971, "Houses of the Holy":1973, "Physical Graffiti": 1975, "Presence":1976, "In Through the Out Door":1979, "Coda":1982]
我想要一本仅包含“齐柏林飞艇...”的新词典(即,齐柏林飞艇,齐柏林飞艇II,...,齐柏林飞艇IV)。
我已经按照https://stackoverflow.com/a/41435190/7384373为Dictionary和Array创建了扩展方法
那么我可以使用字符串“ range of”方法来查找“ Led Zeppelin”,如下所示:
let filtered = studioAlbums.filteredDictionary( { $0.0.range(of: "Led Zeppelin") != nil } )
// print(filtered) output: "["Led Zeppelin IV": 1971, "Led Zeppelin III": 1970, "Led Zeppelin": 1969, "Led Zeppelin II": 1969]\n"
我的问题是对于更复杂的过滤,我更喜欢使用正则表达式(regex),但是我无法用正则表达式找出任何简单的解决方案,比如说最多5行代码。(不包括任何扩展方法)。
我认为这是您正在寻找的扩展名:
extension Dictionary where Key: ExpressibleByStringLiteral, Value: Any {
func filterDictionaryUsingRegex(withRegex regex: String) -> Dictionary<Key, Value> {
return self.filter({($0.key as! String).range(of: regex, options: .regularExpression) != nil}).toDictionary(byTransforming: {$0})
}
}
该扩展限制为类型的字典,<String, Any>
以避免任何“字符串转换为字符串”错误。
结果:
let studioAlbums = ["Led Zeppelin":1969, "Led Zeppelin II": 1969, "Led Zeppelin III": 1970, "Led Zeppelin IV": 1971, "Houses of the Holy":1973, "Physical Graffiti": 1975, "Presence":1976, "In Through the Out Door":1979, "Coda":1982]
let filtered = studioAlbums.filterDictionaryUsingRegex(withRegex: "Led")
// ["Led Zeppelin IV": 1971, "Led Zeppelin III": 1970, "Led Zeppelin ": 1969, "Led Zeppelin II": 1969]
编辑:这确实需要扩展user7367341:筛选字典堆栈溢出问题
extension Array
{
func toDictionary<H:Hashable, T>(byTransforming transformer: (Element) -> (H, T)) -> Dictionary<H, T>
{
var result = Dictionary<H,T>()
self.forEach({ element in
let (key,value) = transformer(element)
result[key] = value
})
return result
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句