參考語義
類是引用型別,這意味著多個變數可以引用同一個例項。
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