let is a lie (sometimes)
You’re more of a video kind of person? I’ve got you covered! Here’s a video with the same content than this article 🍿
“let
is a lie, sometimes”
This is quite a bold statement, so let me explain!
I’m not talking about when you use let
to declare a local constant:
In that case, let
is absolutely not a lie and try as you might you won’t be able to set another value to this constant.
But how about when you use let
to declare a property inside a struct
?
Let’s create a value of that struct
and store it in a variable:
If we try to set a new value to the property, we do get an error just as we expect:
But how about a method call?
Would it be possible for a method to change the value inside that let
property?
As it turns out, the answer is yes!
Because if the method of the struct
is mutating
, then it is allowed to assign a new value to self
, which in turns allows it to set a new value to the let
property!
So in that case, the fact that the property was marked as let
actually gave us a false sense of security.
And the only way to be sure that the value of the property cannot be changed is to declare the variable holding the struct
itself as a let
:
Because, as we just saw, if you only declare the property as a let
then you will have made it harder to change its value, but you won’t have made it impossible!
That’s all for this article, I hope you’ve enjoyed discovering this very tricky behaviour of let
properties within structs!
I have a big thank you to Chris Eidhof of the website objc.io because I heard him say the words « let
is a lie » at WWDC and it only took me 5 months to realise it would make a great title for an article!
Here’s the code if you want to experiment with it:
struct MyStruct {
let value: String
mutating func doSomething() {
self = MyStruct(value: "Something else 😏")
}
}
var myStruct = MyStruct(value: "Hello, World!")
myStruct.doSomething()
print(myStruct.value) // "Something else 😏"