Benefits of immutability
We already know that immutability helps safety and performance, but in a real-world application development, immutability can provide us with more benefits, which will be explained in the following sections.
Thread safety
Immutable objects are useful in multi-threaded applications because multiple threads can act on the data of immutable objects without worrying about changes to the data by other threads.
As immutable objects are closed to change, it is safe to assume that they will stay unchanged while we access the object from different threads. This assumption simplifies most of the multithreading problems that are complex to solve and maintain. For instance, we do not need to think about synchronization/locking mechanisms at all.
Suppose that we have a mutable object that includes a mutable array
of a type, for example, a Product
class that has four properties:
struct Producer { let name: String let address: String } class Product { var name: String...