I've been trying to figure out why it's possible to add objects to a let constant dictionary, but cannot find the answer.
The code below works, but I've always thought of let constants as immutable objects.
Anyone that can shed som light on this?
// 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")
}
In Swift the
let
keyword is used to declare a constant. However, there are some things you need to be aware of depending on if you are declaring a constant for a reference type or a value type.Reference Type
Value Type
Mixture of Reference and Value Types
Generally you wouldn't want to have a reference type property defined on a value type. This is for illustrative purposes.
Since
NSMutableDictionary
is a class, declaring the reference as a constant ensures you cannot change its reference, however its mutable properties can be changed.The comment on your question from @vadian regarding
NSMutableDictionary
should be noted.