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

var arrayb = arraya

if arraya === arrayb
{
    println("arraya is identical to arrayb")
}
else
{
    println("arraya is not identical to arrayb")
}

Why the xcode print "arraya is not identical to arrayb"?

Angelo
  • 533
  • 5
  • 18
  • Looks like a bug, since changing an element in `arraya` updates `arrayb` as well, so clearly they still share the same storage. You should file a bug with Apple. – Greg Jun 13 '14 at 09:08
  • Note that when you use `===`, you're not checking whether the arrays are identical, you're checking if they're the *same array* (which in this case they clearly are, which is why it's a bug). If you want to check if the arrays are *identical*, use `==`. (Just wanted to clear this up, since the wording in the question is ambiguous in this sense) – Greg Jun 13 '14 at 09:10
  • 3
    For what it's worth, changing both variables to be constants makes the condition true. – Mick MacCallum Jun 13 '14 at 09:11
  • possible duplicate of [Check if two arrays share the same elements](http://stackoverflow.com/questions/24109957/check-if-two-arrays-share-the-same-elements) – Connor Pearson Jun 13 '14 at 10:44

2 Answers2

0

Well, it looks like a bug.

Arrays are value types in swift, but copying behaviour slightly different than the other value types like enums,dictionaries.

For arrays, copying only takes place when you perform an action that has the potential to modify the length of the array.

It means that if you want an operation that could change the length of array, copying takes place. Like you add or remove an item, replacing items. In your case, you' re just assigning your array to a new variable. I don't think it's the potential to change the length of array.

limon
  • 3,222
  • 5
  • 35
  • 52
0

After inspecting the functions headers a bit, I realised that

  1. The === operator is normally defined only for objects (AnyObject)

  2. Array is a struct but they have added a === operator for Arrays, too

  /// Returns true iff these arrays reference exactly the same elements.
  func ===<T : ArrayType, U : ArrayType>(lhs: T, rhs: U) -> Bool

In my understanding that should be true for your example, so it actually might be be a bug.

EDIT: This has been fixed in DP2

Sulthan
  • 128,090
  • 22
  • 218
  • 270