In C, although we declare a value as const int a = 5;
, we can pass &a
to a function declared as void someFun(const int *);
.
As a rule of thumb, in C, when the original value is need not to be changed, i) if the size of object is less than or equal to size of pointer, we pass it by value, ii) otherwise we pass it by const reference copying the entire value to a function would take more resources.
But in swift, even though an inout parameter is not modified in a function, we can't pass a value declared as let a = 5
to function declared as someFun(_ z: inout Int) -> ()
. Hence we have to mark z in the function as let. This will copy the entire value to the function. This may cost more if the size of the type of a is big. Is there a workaround to this?
As to my understanding,
Reference Link: https://docs.swift.org/swift-book/LanguageGuide/Functions.html
Edit: As mentioned by @SouravKannanthaB in the comment above, swift can automatically optimize the inout by mimicking the behavior of pass by reference, but i don't believe one can force the optimization to take place.