Check If Swift Dictionary Contains No Values?

后端 未结 4 1053
借酒劲吻你
借酒劲吻你 2021-01-02 07:10

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

4条回答
  •  自闭症患者
    2021-01-02 07:32

    There's the easy way:

    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 }
    

提交回复
热议问题