‘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.

This post was originally posted at https://agrawalsuneet.github.io/blogs/inout-in-swift/ and reposted on Medium on 1st Mar 2019.
class Employee {
var name : String
var age : Int
init(name: String, age: Int){
self.name = name
self.age = age
func changeEmployeeData(emp : Employee){
employee.name = "Suneet"
employee.age = 25
let employee = Employee(name: "Random", age : 10)print(employee.name) //Random
print(employee.age) //10
changeEmployeeData(emp : employee)print(employee.name) //Suneet
print(employee.age) //25

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

var variable: Int = 1func changeNumber (num: Int) {
num = 2
changeNumber(num : variable)

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.

var variable: Int = 1func changeNumber (num:inout Int) {
num = 2
print(num) // 2
changeNumber(num : &variable)

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.





Love podcasts or audiobooks? Learn on the go with our new app.

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
Suneet Agrawal

Suneet Agrawal


More from Medium

Class, Structure and Protocol in Swift

apple/swift-evolution 上關於 guard 的有趣討論

Swift Access Control

Variable Definition, Arrays, Dictionaries and Set Structures in Swift