我一直在试图找出为什么可以将对象添加到let常量字典中,但无法找到答案。
下面的代码可行,但我一直认为将常量作为不可变对象。
任何人都可以解释这个问题吗?
// Create dictionary to allow for later addition of data
let data: NSMutableDictionary = ([
"firstname" : "john",
"lastname" : "doe"
])
// Add email to dictionary if e-mail is not empty
if email != "" {
data.setValue(email, forKey: "email")
}
答案 0 :(得分:4)
在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
是一个类,因此将引用声明为常量可确保您无法更改其引用,但可以更改其可变属性。
应该注意@vadian关于NSMutableDictionary
的问题的评论。