當您在swift中使用類的常量實例時,並不意味着您無法更改類屬性。這意味着你不能在這個不斷
let person = Person(firstName: "Johnny", lastName: "Appleseed")
person = Person(firstName: "John", lastName: "Appleseed") //--->It gets error: Cannor assign to value: 'person' is a 'let' constant
實例化一個新的對象,但你可以創建一個恆定的內部類,並在init設置這個值
class Person {
let firstName: String
let lastName: String
init(firstName: String, lastName: String) {
self.firstName = firstName
self.lastName = lastName
}
func fullName() -> String {
return "\(firstName) \(lastName)"
}
}
//Tip: Don't init the class constants in declaration time or will get the same above error. Just init this constants at constructor/initialization of class.
,現在你有預期的結果你想,即使創建該對象
var person = Person(firstName: "Johnny", lastName: "Appleseed")
person.firstName = "John" //--->It gets error: Cannor assign to value: 'person' is a 'let' constant
person = Person(firstName: "John", lastName: "Snow")
person.firstName = "Johnny" //--->It gets error: Cannor assign to value: 'person' is a 'let' constant
你的想法是沒有錯的「變種」的實例,但有點迷惑,因爲你是完全正確的,如果它是一個結構,而不是一類。
非常感謝您的幫助,非常好的解釋! – SLN
@SLN高興地幫助:) – Hamish