参考语义
类是引用类型,这意味着多个变量可以引用同一个实例。
class Dog {
var name = ""
}
let firstDog = Dog()
firstDog.name = "Fido"
let otherDog = firstDog // otherDog points to the same Dog instance
otherDog.name = "Rover" // modifying otherDog also modifies firstDog
print(firstDog.name) // prints "Rover"
因为类是引用类型,即使该类是常量,仍可以修改其变量属性。
class Dog {
var name: String // name is a variable property.
let age: Int // age is a constant property.
init(name: String, age: Int) {
self.name = name
self.age = age
}
}
let constantDog = Dog(name: "Rover", age: 5)// This instance is a constant.
var variableDog = Dog(name: "Spot", age 7)// This instance is a variable.
constantDog.name = "Fido" // Not an error because name is a variable property.
constantDog.age = 6 // Error because age is a constant property.
constantDog = Dog(name: "Fido", age: 6)
/* The last one is an error because you are changing the actual reference, not
just what the reference points to. */
variableDog.name = "Ace" // Not an error because name is a variable property.
variableDog.age = 8 // Error because age is a constant property.
variableDog = Dog(name: "Ace", age: 8)
/* The last one is not an error because variableDog is a variable instance and
therefore the actual reference can be changed. */
使用 ===
测试两个对象是否相同 (指向完全相同的实例):
class Dog: Equatable {
let name: String
init(name: String) { self.name = name }
}
// Consider two dogs equal if their names are equal.
func ==(lhs: Dog, rhs: Dog) -> Bool {
return lhs.name == rhs.name
}
// Create two Dog instances which have the same name.
let spot1 = Dog(name: "Spot")
let spot2 = Dog(name: "Spot")
spot1 == spot2 // true, because the dogs are equal
spot1 != spot2 // false
spot1 === spot2 // false, because the dogs are different instances
spot1 !== spot2 // true