swiftpass-by-valuepass-by-const-reference

Why can't we pass const values by reference to inout functions in swift?


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?


Solution

  • As to my understanding,

    The 'inout' in swift does not actually send the reference of the property to the function. When you change the value of the property passed as 'inout', the swift on its own end checks if you have changed the value and then performs that change to the actual property on its own. So the only thing 'inout' does in swift is changing the value of the actual property. So even if it allows you to send a constant as 'inout', you still won't be able to make any use of it, because of the very nature of the 'constant'. You just cant change the value of a 'constant', because its immutable.

    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.