添加对象以让常量 NSMutableDictionary 有效,但为什么呢?

Adding object to let constant NSMutableDictionary works, but why?

我一直在试图弄清楚为什么可以将对象添加到 let 常量字典,但找不到答案。

下面的代码有效,但我一直认为 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")
    }

在Swift中,let关键字用于声明常量。但是,根据您是为 reference 类型还是 value 类型声明常量,您需要注意一些事项。

引用类型

// 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 是 class,将引用声明为常量可确保您无法更改其 reference,但可以更改其可变属性。

应注意@vadian 对您关于 NSMutableDictionary 的问题的评论。