Uzumaki Naruto
Uzumaki Naruto

Reputation: 547

Swift Core Data group results into tuples

I have a Core Data table like such:

Core Data Table

How can I use a combination of collection operators in Swift so that the fetch results in array of tuples with definition like this:

[(date: String, values: [Int])]?

For example, the table above would yield:

Optional([("2/1/2016", [2, 3]), ("2/2/2016", [7])])

The second part of the tuple is an array of variable length...

Upvotes: 1

Views: 400

Answers (1)

Uzumaki Naruto
Uzumaki Naruto

Reputation: 547

This is how I did it, without collection (doesn't seem to have a shortcut to doing it with collection operators); basically it's just a nested fetch request:

func dailyitems() -> [(date: String, items: [Item])]?
{
    let request = NSFetchRequest(entityName: ItemEntity);
    request.returnsDistinctResults = true;
    request.resultType = NSFetchRequestResultType.DictionaryResultType;
    request.propertiesToFetch = NSArray(object: "date_string") as [AnyObject];
    var array_tuples : [(date: String, items: [Item])]?;
    var daily_items : [Item] = []

    do
    {
        let distinctResults: NSArray? = try context.executeFetchRequest(request);

        if(distinctResults == nil || distinctResults!.count < 1)
        {
            return nil;
        }

        array_tuples = [];

        for date in distinctResults!
        {

            let Itemrequest = NSFetchRequest(entityName: ItemEntity);
            Itemrequest.predicate = NSPredicate(format: "date_string == %@", date.valueForKey("date_string") as! String);

            do
            {
                let dayitems = try context.executeFetchRequest(Itemrequest) as? [NSManagedObject];

                if(dayitems != nil && dayitems?.count > 0)
                {
                    daily_items = [];

                    for dayItem in dayitems!
                    {
                        daily_items.append(
                            Item(

                                item: dayItem.valueForKey("item") as! String,
                                date: dayItem.valueForKey("date_string") as! String,
                                value: dayItem.valueForKey("value") as! Int,

                            )
                        );
                    }

                    array_tuples?.append((date: date.valueForKey("date_string") as! String, items: daily_items));
                }

            }
            catch
            {
                return nil;
            }
        }

    }
    catch
    {
        return nil;
    }


    return array_tuples;
}

Not sure if there's a more efficient way to do this...

Upvotes: 2

Related Questions