0

This is more a comment than a question.

Academic Question: How do I check if a shorted array is 'different' than its unsorted version?
(...or, is this the standard Sort behavior for an array?)

It appears that the current Array.sort() mutates itself, even though it's technically immutable via the 'let'. That is, a CONSTANT array's contents is mutable as long as the array's length isn't changed.

The following code snippet demonstrates the situation:

let a = [5,4,3,2,1]
let a2 = [5,4,3,2,1]
(a == a2)     // *true*
(a === a2)    // *false*

let b = sort(a)         
a    // [1,2,3,4,5]
b    // [1,2,3,4,5]

(a == b)   // *true*
(a === b)  // *true*

I can understand that (a === a2) is false; being that they're two distinct arrays.

But how can I tell the difference between two arrays, array #1 and it's sorted version?
It appears the sorting an array merely mutates itself; and hence I would have to make a copy and then, use the '==' to check the difference.

Frederick C. Lee
  • 9,019
  • 17
  • 64
  • 105
  • 1
    *"... mutates itself, even though it's technically immutable via the 'let'"* - The rules are different for Swift **arrays**, see for example http://stackoverflow.com/a/24090842/1187415. – Martin R Jun 30 '14 at 20:02
  • 2
    The let keyword makes the reference to the array constant. It doesn't make any requirements about the contents of the array, or other object it might point to. – John M. P. Knox Jun 30 '14 at 21:07

1 Answers1

2

You can force a copy instead of sorting the same array by using copy().

let b = sort(a.copy())
a    // [5,4,3,2,1]
b    // [1,2,3,4,5]

(a == b)   // *false*
(a === b)  // *false*

Arrays have some pretty odd behavior even when assigned to a constant in Swift. Apple has said that they will fix this in a later beta though, so this question and solution may not always be valid.

Connor Pearson
  • 63,902
  • 28
  • 145
  • 142