How can I pass a constant parameter by reference?
In Swift it can be done just for variables (and using inout
keyword).
Can I pass a constant by reference?
I want to do something like this:
let x = ["a":1, "b":2]
myFunc(&x)
How can I pass a constant parameter by reference?
In Swift it can be done just for variables (and using inout
keyword).
Can I pass a constant by reference?
I want to do something like this:
let x = ["a":1, "b":2]
myFunc(&x)
You cannot pass a let
constant to an inout
parameter.
According to Swift reference
In-out parameters are passed as follows:
- When the function is called, the value of the argument is copied.
- In the body of the function, the copy is modified.
- When the function returns, the copy’s value is assigned to the original argument.
This automatically disqualifies let
constants, because they cannot be assigned back.
Can I pass a constant by reference?
Not that I'm aware of. However, you should never need to do so yourself.
In the specific case you raise with a Dictionary
, you're dealing with a collection that stores its contents indirectly. At its simplest level, you can think of it as a structure that just has a single property, which is merely a reference to the actual storage for the keys & values of the dictionary.
Passing that struct, the dictionary, by value is equivalent to just passing a reference about. Multiple dictionaries can view the same key & value storage through that reference. However, a unique copy of the storage will be taken on mutation if necessary – this is called copy-on-write, and allows for value semantics without the overhead of copying the entire buffer every time the dictionary structure is copied.
So for that reason, there is absolutely no need for a pass-by-reference here. Just pass the dictionary normally (i.e by value – that is, not with &
such as with inout
and pointer parameters).
In the more general case of having a large structure that you want to avoid copying when passing by value to a function – the compiler already has you covered. It can perform various clever optimisations to reduce copying; one of which is passing the structure by reference to a function. I go into more detail about this in this Q&A.
It's really not something you should need to think about unless:
You actually need caller-side mutation (in which case, you want a var
anyway).
You've specifically identified a performance bottleneck (in that case, you may well benefit from making your own copy-on-write structure).