引用是不变的吗?

时间:2015-12-12 18:46:17

标签: swift

我有以下代码:

class Employee {

    var name: String = String()
    var surname: String = String()

    init(name: String, surname: String) {

        self.name = name
        self.surname = surname

    }

}

使用let关键字创建一个对象:

let john = Employee(name: "John", surname: "Adams")

我的问题是,这里有什么常量,参考或对象?

1 个答案:

答案 0 :(得分:3)

引用是常量。

事实上,如果你试图改变它

john = Employee(name: "aName", surname: "aSurname")

你得到以下非常明确的编译器错误。

error: cannot assign to value: 'john' is a 'let' constant
john = Employee(name: "aName", surname: "aSurname")
~~~~ ^

另一方面,对象的properties被声明为var并且可以更改

john.name = "another name"