2024-02-16 06:00:05

==和===的差值

在swift中,似乎有两个相等运算符:双等号(==)和三重等号(===),两者之间的区别是什么?


当前回答

!==和===是标识符,用于确定两个对象是否具有相同的引用。

Swift还提供了两个标识操作符(===和!==),用于测试两个对象引用是否都引用同一个对象实例。

摘自:苹果公司《快速编程语言》。“iBooks。https://itun.es/us/jEUH0.l

其他回答

!==和===是标识符,用于确定两个对象是否具有相同的引用。

Swift还提供了两个标识操作符(===和!==),用于测试两个对象引用是否都引用同一个对象实例。

摘自:苹果公司《快速编程语言》。“iBooks。https://itun.es/us/jEUH0.l

简而言之:

==运算符检查它们的实例值是否相等,"equal to"

===运算符检查引用是否指向同一个实例," same to"

长一点的回答:

Classes are reference types, it is possible for multiple constants and variables to refer to the same single instance of a class behind the scenes. Class references stay in Run Time Stack (RTS) and their instances stay in Heap area of Memory. When you control equality with == it means if their instances are equal to each other. It doesn't need to be same instance to be equal. For this you need to provide a equality criteria to your custom class. By default, custom classes and structures do not receive a default implementation of the equivalence operators, known as the “equal to” operator == and “not equal to” operator != . To do this your custom class needs to conform Equatable protocol and it's static func == (lhs:, rhs:) -> Bool function

让我们看一个例子:

class Person : Equatable {
    let ssn: Int
    let name: String

    init(ssn: Int, name: String) {
        self.ssn = ssn
        self.name = name
    }

    static func == (lhs: Person, rhs: Person) -> Bool {
        return lhs.ssn == rhs.ssn
    }
}

附注:由于ssn(社会安全号码)是一个唯一的号码,你不需要比较他们的名字是否相等。

let person1 = Person(ssn: 5, name: "Bob")
let person2 = Person(ssn: 5, name: "Bob")

if person1 == person2 {
   print("the two instances are equal!")
}

尽管person1和person2引用在Heap区域中指向两个不同的实例,但它们的实例是相等的,因为它们的ssn号码是相等的。因此输出将是两个实例相等!

if person1 === person2 {
   //It does not enter here
} else {
   print("the two instances are not identical!")
}

===运算符检查引用是否指向同一个实例," same to"。因为person1和person2在Heap区域中有两个不同的实例,所以它们不相同,两个实例的输出也不相同!

let person3 = person1

注:类是引用类型,person1的引用通过赋值操作被复制到person3,因此两个引用指向Heap区域中的同一个实例。

if person3 === person1 {
   print("the two instances are identical!")
}

它们是相同的,并且输出将是两个实例是相同的!

==用于检查两个变量是否相等 2 == 2。但是在===的情况下,它代表相等,即如果两个实例引用同一个对象示例,在类的情况下,一个引用被创建,由许多其他实例持有。

例如,如果你创建一个类的两个实例,例如myClass:

var inst1 = myClass()
var inst2 = myClass()

你可以比较这些例子,

if inst1 === inst2

引用:

用于测试两个对象引用是否都引用 相同的对象实例。

摘自:苹果公司《快速编程语言》。“iBooks。https://itun.es/sk/jEUH0.l

在swift 3及以上

===(或!==)

检查两个值是否相同(都指向相同的内存地址)。 比较引用类型。 Like ==在Obj-C(指针相等)。

==(或!=)

检查值是否相同。 比较值类型。 就像Obj-C行为中的默认isEqual:一样。

这里我比较了三个实例(类是引用类型)

class Person {}

let person = Person()
let person2 = person
let person3 = Person()

person === person2 // true
person === person3 // false