ios Swift:过滤字典
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/32604897/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Swift: filter dictionary
提问by warly
i am trying to filter a dictionary in swift:
我正在尝试快速过滤字典:
var data: [String: String] = [:]
data = data.filter { let data = ["a": 0, "b": 42]
let filtered = data.filter { let data: [String: String] = [:]
let filtered = data.filter { var newData = [String:String]()
for result in filtered {
newData[result.0] = result.1
}
.1 == "Test" }
.value > 10 }
print(filtered) // ["b": 42]
.1 == "Test" }
the filter code above compiles under swift 2 but yields the following error:
上面的过滤器代码在 swift 2 下编译,但产生以下错误:
Cannot assign a value of type '[(String, String)]' to a value of type '[String : String]'
无法将“[(String, String)]”类型的值分配给“[String : String]”类型的值
is this a bug in the swift compiler or is this not the right way to filter dictionaries in swift?
这是 swift 编译器中的错误还是这不是在 swift 中过滤字典的正确方法?
Thank you very much in advance!
非常感谢您提前!
回答by Eric Aya
This has been fixed in Swift 4
这已在 Swift 4 中修复
var data = ["a":"Test", "b":"nope"]
for (key, value) in data {
if value != "Test" {
data.removeValueForKey(key)
}
}
print(data) // ["a": "Test"]
In Swift 4, a filtered dictionary returns a dictionary.
在 Swift 4 中,过滤后的字典会返回一个字典。
Original answer for Swift 2 and 3
Swift 2 和 3 的原始答案
The problem is that data
is a dictionary but the result of filter
is an array, so the error message says that you can't assign the result of the latter to the former.
问题是这data
是一个字典,但结果filter
是一个数组,所以错误消息说你不能将后者的结果分配给前者。
You could just create a new variable/constant for your resulting array:
您可以为结果数组创建一个新的变量/常量:
data.forEach { if != "Test" { data[extension Dictionary
{
func filteredDictionary(_ isIncluded: (Key, Value) -> Bool) -> Dictionary<Key, Value>
{
return self.filter(isIncluded).toDictionary(byTransforming: { let data = ["a":"yes", "b":"nope", "c":"oui", "d":"nyet"]
let filtered = data.filteredDictionary({ extension Array {
func dictionary<K: Hashable, V>() -> [K: V] where Element == Dictionary<K, V>.Element {
var dictionary = [K: V]()
for element in self {
dictionary[element.key] = element.value
}
return dictionary
}
}
.1 >= "o" })
// filtered will be a dictionary containing ["a": "yes", "c": "oui"]
})
}
}
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
}
}
] = nil } }
Here filtered
is an array of tuples: [(String, String)]
.
这里filtered
是元组的数组:[(String, String)]
。
Once filtered, you can recreate a new dictionary if this is what you need:
过滤后,如果这是您需要的,您可以重新创建一个新字典:
dictionary = dictionary.filter{ ##代码##.key == "test" }.dictionary()
If you decide not to use filter
you could mutate your original dictionary or a copy of it:
如果你决定不使用,filter
你可以改变你的原始字典或它的副本:
Note: in Swift 3, removeValueForKey
has been renamed removeValue(forKey:)
, so in this example it becomes data.removeValue(forKey: key)
.
注意:在 Swift 3 中,removeValueForKey
已经被重命名removeValue(forKey:)
,所以在这个例子中它变成了data.removeValue(forKey: key)
.
回答by Eendje
Just another approach (a bit simplified) to filter out objects in your dictionary.
这是过滤字典中对象的另一种方法(稍微简化)。
回答by user7367341
Per Apple docs, filter:
根据 Apple 文档,过滤器:
Returns an array containing, in order, the elements of the sequence that satisfy the given predicate.
返回一个按顺序包含满足给定谓词的序列元素的数组。
https://developer.apple.com/reference/swift/sequence/1641239-filter
https://developer.apple.com/reference/swift/sequence/1641239-filter
I found myself needing to do what the OP was asking about and ended up writing the following extensions (Swift 3):
我发现自己需要做 OP 所要求的事情,并最终编写了以下扩展(Swift 3):
##代码##Usage:
用法:
##代码##回答by Gregory Higley
I've found this method to be useful after filtering or applying some other transform that results in an array of dictionary elements:
我发现在过滤或应用一些其他导致字典元素数组的转换后,此方法很有用:
##代码##To use it, just say something like:
要使用它,只需说如下:
##代码##The advantage of this method is that no argument of any kind needs to be passed to the dictionary()
method. Generic type arguments tell the compiler everything it needs to know.
这种方法的优点是不需要将任何类型的参数传递给dictionary()
方法。通用类型参数告诉编译器它需要知道的一切。
回答by Yogesh Patel
Please check for complex dictionary like array of dictionary I hope it helps you !! Thank You
请检查复杂的字典,如字典数组,希望对您有所帮助!!谢谢你