Tao
Tao

Reputation: 287

Identity operators in Swift

If a is identical to c, b is identical to c, why a is not identical to b?

var a = [1, 2, 3]
var b = a
var c = a[0...2]
a === c                    // true
b === c                    // true
a === b                    // false

If a, b, c are constants:

let a = [1, 2, 3]
let b = a
let c = a[0...2]
a === c                    // true
b === c                    // true
a === b                    // true

Upvotes: 5

Views: 1024

Answers (3)

shucao
shucao

Reputation: 2242

As @onevcat said, it's might be a bug of Playground. And if you change a to objects of reference type, all the identity tests will be true.

class K {}
var a = [K(), K(), K()]
var b = a
var c = a[0...2]
a === c                    // true
b === c                    // true
a === b                    // true

it means that a, b & c share the same storage and elements.

Upvotes: 0

onevcat
onevcat

Reputation: 4631

You can remove the import Cocoa or import UIKit if you are playing with PlayGround to make it correct. It seems there is some type map thing in the Cocoa framework to mess things up. It should be a bug, I think.

Upvotes: 2

Jack
Jack

Reputation: 16855

Interesting, my guess is that since c is a var in the first case, its mutable and thus it has to make a copy. That way if you add on to c it wouldn't modify a. In the second case, they are all immutable so they can point to the same memory space

Upvotes: 0

Related Questions