‘inout’ in Swift

Recently, while working with swift I came up with a use case where I need to modify the variable passed as an argument to a function. Eventually, all the variables passed to a function are of an immutable type which cannot be changed which is similar to a let variable. If it’s a class object, you cannot create a new object but you can manipulate the properties of that class object or you can call any function with that object.

Now the problem occurs when your argument is of primitive data type, you simply can’t change the value.

It will show the error “cannot assign to value: ‘num’ is a ‘let’ constant” which is self-explanatory. We can’t modify the parameter passed as an argument as those are of let type.

Now, what if I want to modify this value?

inout to the rescue.
You can use inout where it passes the parameter as a reference.

You need to add inout before the datatype of the variable and an & while passing the parameter.

Please continue reading at https://agrawalsuneet.github.io/blogs/inout-in-swift/

That’s all for now. You can read my other interesting posts here or you can enjoy my games or apps listed here. Feel free to use my open-source Android components in your app listed here. Or drop an email, if you didn’t find what you are looking for and need some help.

--

--

https://agrawalsuneet.github.io/

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store