Home > Software engineering >  Pass Array or FetchedResults as an argument to method
Pass Array or FetchedResults as an argument to method

Time:12-20

I have two identical methods that differ in the argument they receive. One receives an Array<Entity> and the other one a FetchedResults<Entity> object, where Entity is a CoreData Entity. It would be nice to simplify code by removing the duplication and only having one method.

    static func groupByDate(_ result : FetchedResults<Entity>)-> [[Entity]]{
        return  Dictionary(grouping: result){ $0.dateDescription }
            .values
            .map{$0}
            .sorted(by: { $0.first!.timestamp! > $1.first!.timestamp! })
    }
    
    static func groupByDate(_ result : [Entity])-> [[Entity]]{
        return  Dictionary(grouping: result){ $0.dateDescription }
            .values
            .map{$0}
            .sorted(by: { $0.first!.timestamp! > $1.first!.timestamp! })
    }

I tried to use a sequence of the Entity type to abstract the method because both Array<Entity> and FetchedRusults<Entity> adhere to the protocol. Unfortunately, I wasn't able to get it to work.

I'm curious how you would solve it.

CodePudding user response:

Both FetchedResults and Array conform to the Sequence protocol so you can use that as a generic type and have a where condition to only allow Sequence types that has Entity as it content

static func groupByDate<Values: Sequence>(_ result: Values) -> [[Entity]] where Values.Element == Entity {
    return Dictionary(grouping: result, by: { $0.dateDescription })
        .values
        .sorted(by: { $0.first!.timestamp! > $1.first!.timestamp! })
}
  • Related