-
Hello 👋, I wonder why the I know the current return value of |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 10 replies
-
The return value as a tuple or a struct that contains the state and an effect looks clumsy. |
Beta Was this translation helpful? Give feedback.
-
Hi @lo1tuma, Swift has a few features that Javascript does not have that makes this "mutation" completely safe, and even equivalent to return a whole new value. First, Swift has values types, which are types that are copied when passed to function. This means if you copy the value and mutate it in your function, it did not make any changes to the original value passed to the function. That local mutation is completely quarantined to just the function. This is in stark contrast to reference types (e.g. classes and essentially all of JS's types), in which objects are passed by their reference to functions. This means any change made to the object in the function is instantly visible to anyone else holding a reference to that object. Such mutations can affect objects in many parts of the application at once, and it can be difficult (if not impossible) to know who all will be affects. So, that's one feature Swift has that JS doesn't. There's another one that pairs well with value types, and it's called func doSomething(state: State) -> State {
var state = state
state.field = …
…
return state
} Swift allows you to shorten that into its equivalent form using func doSomething(state: inout State) {
state.field = …
…
} No need to specify a return type, no need to make a copy and no need to return the copy. These two forms are completely equivalent. One is no safer than the other thanks to Swift's value types. However, ergonomics wise, one is clearly better since the |
Beta Was this translation helpful? Give feedback.
Hi @lo1tuma, I have some responses below:
Mutable-by-default is not the only problem with JS objects, and in fact it's kinda the least pernicious. The real problem with JS objects is that they are reference types, and so that when you do mutate them, that mutation is visible to everyone holding a reference and you can never know who mutate…