I have a Match object which contains a 'row' property and a 'column' property. I then have a Set<Match> with a bunch of those entities. I want to get a "matchesByColumnAndRow" variable that's an array of arrays. So the first element would be an array, sorted by 'row', containing the smallest value for column (In this case 'column' property can have negative numbers, which is why I say smallest, vs. 0)
I have this working via the following code, but I really don't like it. First it sorts into a flat array by column and then row, and then it creates the array of arrays. Technically it's not wrong, and I'm not so worried about performance, but I'm just wondering if there's a cleaner way to do this.
private lazy var matchesByColumnAndRow: [[Match]] = {
let sorted = self.matches.sort {
switch ($0.0, $0.1) {
case let (lhs, rhs) where lhs.column == rhs.column:
return lhs.row < rhs.row
case let (lhs, rhs):
return lhs.column < rhs.column
}
}
var byColumnAndRow: [[Match]] = []
var cur: [Match] = []
var prevColumn = Int.min
for match in sorted {
if match.column != prevColumn {
if prevColumn != Int.min {
byColumnAndRow.append(cur)
cur = []
}
prevColumn = match.column
}
cur.append(match)
}
return byColumnAndRow
}()