0

I have an array with playing cards. I would like to sort these on value, color and playability.

  • I have 4 colors; 1, 2, 3, 4.
  • I have 3 playability options; 1, 2, 3.
  • I have 5 values; 1, 2, 3, 4, 5.

I am able to sort the array on color and value. So if the color is the same, the array is sorted on value.

example color-value pairs:

1-2, 1-4, 1-5, 2-2, 3-1, 3-2, 3-5

Code is,

playerCards.sort {
       if $0.colorSorter == $1.colorSorter {
            return $0.value < $1.value
       }
        return $0.colorSorter < $1.colorSorter
    }

How do I add the third paramater to sort on playability additionally?

What I would like to see (playability-color-value triplets):

1-1-2, 1-1-4, 1-2-2, 1-3-1, 2-1-5, 2-3-1, 2-3-2, 3-3-5

1: sort on playability 2: sort on color 3: sort on value.

Thanks!

nipunasudha
  • 2,427
  • 2
  • 21
  • 46
Niels
  • 115
  • 11

1 Answers1

0

Assuming this is your struct

struct Card {
    let color:Int
    let value:Int
    let playability:Int
}

and this is your array

let cards:[Card] = ...

You can sort cards by

  1. playability
  2. color
  3. value

writing

let sorted = cards.sorted { (left, right) -> Bool in
    guard left.playability == right.playability else { return left.playability < right.playability }
    guard left.color == right.color else { return left.color < right.color }
    return left.value < right.value
}
Luca Angeletti
  • 58,465
  • 13
  • 121
  • 148