1

If I have:

var arrayOne = ["dog", "cat", "hamster", "horse"]​ and

var arrayTwo = [3, 2, 4, 1]

How can I assign 3 to dog, 2 to cat, 4 to hamster, and 1 to horse so that if I sort arrayTwo from biggest integer to smallest, it will automatically do that for arrayOne too. In result it would print out:

var arrayOne = ["hamster", "dog", "cat", "horse"]

var arrayTwo = [4, 3, 2, 1]

What code is easiest and simplest for this?

Thanks in Advance! :)

Raven
  • 33
  • 4
  • 1
    Keep them in one array, with a tuple, or another object (dictionary, custom struct/object, etc.). Don't keep 2 arrays that's exactly the best way to keep them desynchronized. – Larme Apr 21 '18 at 17:20
  • You better define an `Animal` struct or class with two properties: `id` and `name`. Arrays can get confusing really quick – Code Different Apr 21 '18 at 17:25
  • This was interesting to try and by the time I came back, the question was closed but anywho... here's what I came up with: https://gist.github.com/staticVoidMan/19175de6ea9021eaa27d3b5cf4d432ba – staticVoidMan Apr 21 '18 at 18:13

1 Answers1

1

It's quite hard to "bind" the two variables together. You could do something like this:

let dict = [3: "dog", 2: "cat", 4: "hamster", 1: "horse"]

var arrayTwo = [3, 2, 4, 1] {
    willSet {
        // you should probably check whether arrayTwo still has the same elements here
        arrayOne = newValue.map { dict[$0]! }
    }
}

It is easier to zip the arrays and then sort by arrayTwo:

let result = zip(arrayOne, arrayTwo).sorted(by: { $0.1 > $1.1 })

Now, result.map { $0.0 } is your sorted array 1 and result.map { $0.1 } is your sorted array 2.

Sweeper
  • 213,210
  • 22
  • 193
  • 313