Patty Patty - 2 months ago 13x
Swift Question

Combining two arrays and sorting the arrays Swift

I am looking to do something along the lines of combining two arrays of different types. Essentially I am trying to do something like this

var alphabet = [b,c,a,e,f,d]
var numbers = [2,3,1,5,6,4]

as you can see, the numbers and letters already correspond with each other in the list above, they are just out of place.

I would like it spit out the letters and numbers in order such as


I would appreciate the help, Thank you

  • zip the two arrays, that gives you an array of tuples (pairs) [(b, 2), (c, 3), ... ].
  • Sort that array of tuples with respect to the first component:

Swift 2 code:

let result = zip(alphabet, numbers).sort { $0.0 < $1.0 }
print(result) // [("a", 1), ("b", 2), ("c", 3), ("d", 4), ("e", 5), ("f", 6)]