I tried searching for guidance on this topic but all I could find were introductory discussions about var, let, and mutability in Swift. I've been doing some reading on OOP vs FP, and trying to better understand the benefits of immutability and when to best require it.
Our code base has a lot of model data stored in structs where all the properties are let
, and some structs where the properties are var
. I find the latter easier to use, in practice, because it means I can change one property of a struct without jumping through a lot of hoops.
Case in point: I just added code in our app to allow the user to change their profile image. After writing the image to the server, I update the user model's profile image URL, and SwiftUI ensures that the display is reloaded to reflect the new image. Unfortunately, the user struct was one of the all-let
ones, and in the interests of time, I modified that one property to be var
.
Which got me thinking, is there a good rule of thumb as to when one should use let or var in struct properties? Using var lets the type user dictate if it's mutable or not. It also makes it easier to create a copy of an immutable instance and update a subset of properties (I saw a talk about lenses that let you do this concisely with immutable structs if they all had memberwise initializers, but we don't have that).