0

Considering the date model below :

struct Order: Hashable {
    let mode: Mode
    let title: String
}

enum Mode {
case old, new, middle
}

I am using the basic swift grouping method in order to creating an array of arrays split by the mode property of the object.

func groupByMode(_ orders: [Order]) -> [[Order]] {
    return Array(Dictionary(grouping: orders) { $0.mode }.values)
}

The array below :

let orders = [Order(mode: .new, title: "shirt1"), Order(mode: .new, title: "shirt2"), Order(mode: .new, title: "shirt3"), Order(mode: .old, title: "shirt4"), Order(mode: .old, title: "shirt5"), Order(mode: .middle, title: "shirt6")]

Becomes this array of arrays :

let orderArrayofArrays = [[Order(mode: .new, title: "shirt1"), Order(mode: .new, title: "shirt2"), Order(mode: .new, title: "shirt3")], [Order(mode: .old, title: "shirt4"), Order(mode: .old, title: "shirt5")], [Order(mode: .middle, title: "shirt6")]]

This works pretty well with an array of couple of objects, but becomes longer and problematic regarding to the performances with a bigger range of data. Is that existing a way to optimize this algorithm ?

Blisko
  • 107
  • 2
  • 9

0 Answers0