Did you know in Swift you can change “let” properties within a struct? All you have to do is assign self to a new instance with the altered property. Why not just make the property “var” in the first place? Well, by marking it as “let” you can enforce that all changes to the property must go through an initializer. In this example, we only ever want Positive to hold (as the names suggests) positive values. This is done in the initializer but if we want to update the wrapped value we would need to call the same logic again… and we may give room for it to be non positive (besides the repetition). Instead we just pass it to the constructor. This constructor serves as the one and only way to modify the value (hence making it safer, more controlled and predictable). Have you used this technique before?
that works ok with a few properties... try that with a 30 members struct and it aint' so much fun anymore.
While functionally “changing” let, it’s semantically creating an entirely new instance and putting it in the same location. That’s generally…unnecessary, especially for a struct. A better approach would be having ‘private(set) var value’ and then increment can just be ‘value += 1’. That gives you the same external usage pattern, but more efficiently!
Please avoid this kind of code. I know you want to push the limits but at what cost? This could hide a dangerous bug 🐜 for your colleagues in the future.
When you have 60 developers all working on the same code base, this will confuse at least half of them. Making the member a var won’t confuse any of them.
I didn’t know about this. Pretty cool.
Yes i know🙂 but this is not recommended
So... let x = Positive(42) x?.increment() // compiler error
Consider having a lot properies as a part of struct and you are changing a single property here.
Is this because it is creating a new value by destroying the past one with its mutation? I've never done this before, I thought if I wanted to make updates over time I needed to declare a variable instead of a constant, thanks for sharing this technique!
IOS Developer - Tech Lead
10moYou do not change "change" property with struct, you create a new object struct, and replace the current object with new. Sorry, but all I see it's a bad hack, like "create property in extension with static dict"