5 ms·
> Constants are defined via let, and variable are allowed to vary through a var. Though constants are lame, as only the binding itself is constant and you can c
by i_s 11y ago
> Constants are defined via let, and variable are allowed to vary through a var. Though constants are lame, as only the binding itself is constant and you can change everything inside them as usual.
That is at best misleading, as it is not true for collections. From the Swift docs:
> If you create an array, a set, or a dictionary, and assign it to a variable, the collection that is created will be mutable. This means that you can change (or mutate) the collection after it is created by adding, removing, or changing items in the collection. If you assign an array, a set, or a dictionary to a constant, that collection is immutable, and its size and contents cannot be changed.
Swift is the only language that I've seen that actually does make a distinction depending on the keyword used.
- krisdol 11y agoRust does this as well, just FYI.
- Someone 11y agoIt also is one of the only languages where collections are value types. And it has to, to make 'let' create truly immutable objects. Without them, this: var a = [1,2,3] let b = a a += [4,5,6] would change b.
- lionet 11y agoYou are correct. But in FP, we understand immutability differently, so it becomes very painful to watch structural equivalence of the following variables: class Foo { var x = 0 } let a = [Foo(), Foo(), Foo()] var b = a a[0].x = 1 var c = b // [0].x == 1 ;( let d = a // [0].x == 1 ;(