0
votes

I am using Swift and Firebase. I'm currently storing my firebase snapshot objects in a global dictionary. The idea is to then filter those objects based on the value of one or more of their keys.

For example, the pendingFilter() might return all those objects whose "pending" key is equal to true, and ignore the rest.

Array is created like this:

var array = [NSDictionary]()

All objects are appended as AnyObject.

My current dictionary looks something like this:

[{
    accepted = false;
    cancelled = false;
    id = "1";
    pending = true;

}, {
    accepted = false;
    cancelled = false;
    id = "2";
    pending = true;

}, {
    accepted = true;
    cancelled = false;
    id = "3";
    pending = false;
}]

In my filter function, I know I can iterate over each item with a for-in, but how would one go about then filtering by key values for the objects themselves? Is there a preferred Swifty way of doing this? I know about (key, value) in item, but this seems strictly geared towards dictionaries and not objects.

Thanks for your help...

1

1 Answers

3
votes

You can use filter to have only dictionaries with the value of the key pending set to true.

var pendingFilter: [NSDictionary] {
    return array.filter { $0.value(forKey: "pending") as? Bool == true }
}