Home > Software engineering >  swift sort array of dictionary by a fixed value
swift sort array of dictionary by a fixed value

Time:08-25

I have an array like this

@Published var allGroup: [GroupModel] = [
GroupModel(id: UUID().uuidString, groupId: "", groupName: "Personale", subscribers: [], groupCurrency: "", groupCreatedBy: "", groupCreditCards: [], creationDate: Timestamp(date: Date.now), groupColorRed: 0, groupColorBlu: 0, groupColorGreen: 0),

GroupModel(id: UUID().uuidString, groupId: "", groupName: "Famiglia", subscribers: [], groupCurrency: "", groupCreatedBy: "", groupCreditCards: [], creationDate: Timestamp(date: Date.now), groupColorRed: 0, groupColorBlu: 0, groupColorGreen: 0)

]

and I want to sort and has as first item of the array always the group with name Famiglia

I have try like that but give me error: For-in loop requires 'GroupModel' to conform to 'Sequence'

func sortGroupList(groups: [GroupModel]) -> [GroupModel] {
      
      var startGroups = groups
      for group in startGroups {
          for groupName in group {
                if groupName.value == "Famiglia" {
                    startGroups.removeAll(where: { $0 == group })
                    startGroups.insert(group, at: 0)
                }
            }
        }
    }

how is possible to achieve that? thanks

CodePudding user response:

you could try this:

func sortGroupList(groups: [GroupModel]) -> [GroupModel] {
    return groups.sorted(by: { first, _ in
        first.groupName == "Famiglia"
    })
}

and use it like this:

var result = sortGroupList(groups: allGroup)
print("\n---> result: \(result)")
  • Related