Swift arrays identity "Type does not conform to protocol" AnyObject "" error

I am creating a playground and writing this code:

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

a === b

      

And the playground is giving me an error Type '[Int]' does not conform to protocol 'AnyObject'

.

What am I doing wrong?

I am using XCode 6 GM Seed.

UPDATE

This code was taken from the book "The Rapid Programming Language", which states:

"Check whether two arrays or subarrays share the same storage and elements by comparing them with the identity operators (=== and !==)."

      

For more information, see the Classes and Structures chapter.

UPDATE 2 The excerpt was from an older version of the book for the early Swift spec. I downloaded fresh, and there are no such words. Thus, identification operators can only be applied to instances of the class.

+3


source to share


2 answers


According to Swift Programing Language:

"Identical" (represented by three equal signs or ===] means that two constants or variables of the class type refer to the same instance of the class.

In Swift, arrays are structures. Therefore, you cannot use ===

to compare one array to another. Otherwise, the following code - using NSArray - works fine and gives no error messages in the Playground:

var a = [1, 2, 3] as NSArray //NSArray is not a Struct
var b = a
a === b //true

      



This is explained in Swift Programing language:

String instances are always passed by value, and class instances are always passed by reference.

Of course, Identical (===) does not have the same purpose as Equal (==), which helps you check that two instances are considered "equal" or "equivalent" in value. For example, the following code will compile in Playground without an error message:

var a = [1, 2, 3]
var b = a
a == b //true

      

+3


source


===

is identical to the operator and is available only for instances of the class. An array is a structure, so there is no function for this operator. I could agree that the error message is not enough to describe.



Use ==

to compare arrays for equality.

+2


source







All Articles