Swift中==和===的区别
大家好!请解释一下Swift中==和===运算符之间的根本区别?我知道两者都用于比较,但当我尝试比较两个class实例时,结果与预期不符。
以下是我感到困惑的代码示例:
class Person {
var name: String
init(name: String) {
self.name = name
}
}
let person1 = Person(name: "Alice")
let person2 = Person(name: "Alice")
print(person1 == person2) // 编译错误:Binary operator '==' cannot be applied to two 'Person' operands
print(person1 === person2) // false
let person3 = person1
print(person1 === person3) // true我原本期望person1 == person2返回true,因为它们有相同的名字,但得到了编译错误。而===可以工作,但返回false,尽管对象看起来相同。我已经尝试过:
- 添加