gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-11-01 06:17:31 24 4
gpt4 key购买 nike

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

下面的代码有效,但我一直认为 let 常量是不可变对象(immutable对象)。

任何人都可以阐明这一点?

        // 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 关键字用于声明常量。但是,根据您是为引用 类型还是 类型声明常量,您需要注意一些事项。

引用类型

// 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 的问题的评论。

关于swift - 添加对象以让常量 NSMutableDictionary 有效,但为什么呢?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41201569/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com