Check If Swift Dictionary Contains No Values?

18,615

Solution 1

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 }

Solution 2

You can just use isEmpty

var dict: Dictionary<Int, String> = [:]

var result = dict.isEmpty

result will be true

Solution 3

A functional programming approach:

let allEmpty = arr.reduce(true) { $0 && $1.1.isEmpty }

If you're not a big fan of implicit closure arguments, you can of course name them:

let allEmpty = arr.reduce(true) { empty, tuple in empty && tuple.1.isEmpty }
Share:
18,615
Rohan Singh
Author by

Rohan Singh

Currently a student. I like math, computer science, physics, and astronomy. I like bike, run swim, and most of all, hike.

Updated on July 01, 2022

Comments

  • Rohan Singh
    Rohan Singh almost 2 years

    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?

  • Rohan Singh
    Rohan Singh over 8 years
    I believe isEmpty also checks for keys in the dictionary. I just want to check if the keys' values, which are arrays, are empty.
  • Rohan Singh
    Rohan Singh over 8 years
    Thank you! Is the run time different between these three?
  • Rob Napier
    Rob Napier over 8 years
    The first will walk through all of the elements. The second two will stop checking when they find the first non-empty.
  • Rohan Singh
    Rohan Singh almost 8 years
    Okay so worst case they are the same