检查Swift字典是否不包含任何值? [英] Check If Swift Dictionary Contains No Values?
问题描述
所以我正在做一个待办事项列表应用程序,我希望在所有购物商品都被删除后得到通知.我有一本字典,其中包含String:store作为键和[String]:items作为值.有没有一种快速的方法来检查所有项目的数组是否为空?
So I'm making a to-do list app, and I want the user to be notified when all of the shopping items have been deleted. I have a dictionary that contains the String:store as a key and the [String]:items as the values. Is there a fast way to check if all of the items' arrays are empty?
推荐答案
有一种简单的方法:
dicts.values.flatten().isEmpty
但这将遍历所有列表,而没有任何快捷方式.通常,这实际上不是问题.但是,如果您要在发现一个非空值的情况下纾困:
But that will walk through all the lists without any shortcuts. Usually that's really not a problem. But if you want to bail out when you find a non-empty one:
func isEmptyLists(dict: [String: [String]]) -> Bool {
for list in dicts.values {
if !list.isEmpty { return false }
}
return true
}
当然,您可以使它更加通用,以实现快捷和便捷:
Of course you can make this much more generic to get short-cutting and convenience:
extension SequenceType {
func allPass(passPredicate: (Generator.Element) -> Bool) -> Bool {
for x in self {
if !passPredicate(x) { return false }
}
return true
}
}
let empty = dicts.values.allPass{ $0.isEmpty }
这篇关于检查Swift字典是否不包含任何值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!