“There has to be a better way”
99% of all developers have this thought at some point in their career.
One such thought paved the way for this article, the keyword inout in Swift.
Long story short.
If you got plans to alter a parameter within the scope of same function, you either need to copy them and do it internally or you can use this inout, simple as that.
A bit more explanation with codes please?
Function functionFoo with parameter which takes argument as an Int, and I want to update the value of it. So I tried above and got the compiler error saying that the argument which I have is a let constant. Now “There has to be a better way”, than me copying to a different variable and then update it.
inout to the rescue!!
I tried putting inout keyword to parameter telling the function that I will alter this parameter within the scope. Compiler still not happy with what I did, for I was sending a constant/literal as functionFoo(&10).
Now what is the problem passing a constant or literal as an argument along with ampersand(&)? As everyone already knows constants and literals cannot be modified. So as with this function too.
So the correct way to do is:
Now I passed argument as var to function with ampersand(&) as perfix, telling functionFoo that I will update this parameter in your scope. All good and now you can see the parameter is updated within the scope without any warnings.
All seems good now.
You can refer more about inout and functions refer HERE
Like to read on How to create an Umbrella Framework in iOS?