在 Swift 中,let
关键字用于声明一个常量。但是,根据您是为引用类型还是值类型声明常量,您需要注意一些事项。
参考类型
// Declare a class (which is a reference type)
class Foo {
var x = 1
}
// foo's reference is a constant.
// The properties are not unless they are themselves declared as constants.
let foo = Foo()
// This is fine, we are not changing the foo reference.
foo.x = 2
// This would result in a compiler error as we cannot change
// the reference since foo was declared as a constant.
foo = Foo()
值类型
// Declare a struct (which is a value type)
struct Bar {
var y = 1 // Note the var
}
// bar's value is a constant. The constant nature of the value type properties
// that are part of this value are subject to bar's declaration.
let bar = Bar()
// This would result in a compiler error as we cannot change
// the value of bar.
bar.y = 2
引用类型和值类型的混合
通常,您不希望在值类型上定义引用类型属性。这是为了说明目的。
// Declare a struct (which is a value type)
struct Car {
let foo = Foo() // This a reference type
}
// The value is a constant. But in this case since the property foo
// is declared as a constant reference type, then the reference itself
// is immutable but its x property is mutable since its declared as a var.
let car = Car()
// This is fine. The x property on the foo reference type is mutable.
car.foo.x = 2
由于NSMutableDictionary
是一个类,将引用声明为常量可确保您无法更改其引用,但可以更改其可变属性。
NSMutableDictionary
应注意@vadian 对您的问题的评论。