Charlotte
Charlotte

Reputation: 135

Check if two arrays share the same elements

I've written this code in a .playgraound

var a = [1, 2, 3]
var b = a
var c = a

if b === c
{
    "b and c still share the same array elements."
}
else
{
    "b and c now refer to two independent sets of array elements."
}

The result is "b and c now refer to two independent sets of array elements" but in "The Swift Programming Language" Apple says that

The example below uses the “identical to” operator (===) to check whether b and c still share the same array elements.

Can you explain me why they are different?

Upvotes: 1

Views: 906

Answers (2)

nathan
nathan

Reputation: 5506

b === c tests what will happen to c if you change one of the elements of b or vice versa. In your example, b === c evaluates to true, so when you change an element of b:

var a = [1, 2, 3]
var b = a
var c = a

b[1] = 10

you see the change reflected in c:

c[1] // returns 10

You can use the unshare() method to ensure that b refers to an independent array instance:

b.unshare()
b === c // returns false

b[2] = 10
c[2] // returns 3

Upvotes: 0

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726579

The reason the book says

The result is "b and c now refer to two independent sets of array elements"

is that the code earlier in the book stopped array sharing between b and c established by the assignment of a to both of them:

b.unshare() // Page 306, line 3

Array a has been unshared from b and c implicitly by appending an element to it on page 305, line 1.

With the code as you show the "b and c still share the same array elements." message will be printed.

Upvotes: 2

Related Questions