When passing a class or primitive type into a function, any change made in the function to the parameter will be reflected outside of the class. This is basically the same thing an inout
parameter is supposed to do.
What is a good use case for an inout parameter?
An inout parameter is a special type of parameter that can be modified inside a function and the changes apply outside the function.
Use the in mode if you want to pass a value to the function. Use the out mode if you want to return a value from a function. Use the inout mode when you want to pass in an initial value, update the value in the function, and return it updated value back.
All parameters passed into a Swift function are constants, so you can't change them. If you want, you can pass in one or more parameters as inout , which means they can be changed inside your function, and those changes reflect in the original value outside the function.
Not in the PL/SQL. A function can have OUT or IN OUT parameters, but this is bad coding practice. A function should have a return value and no out parameter. If you need more than one value from a function you should use a procedure.
inout
means that modifying the local variable will also modify the passed-in parameters. Without it, the passed-in parameters will remain the same value. Trying to think of reference type when you are using inout
and value type without using it.
For example:
import UIKit var num1: Int = 1 var char1: Character = "a" func changeNumber(var num: Int) { num = 2 print(num) // 2 print(num1) // 1 } changeNumber(num1) func changeChar(inout char: Character) { char = "b" print(char) // b print(char1) // b } changeChar(&char1)
A good use case will be swap
function that it will modify the passed-in parameters.
Swift 3+ Note: Starting in Swift 3, the inout
keyword must come after the colon and before the type. For example, Swift 3+ now requires func changeChar(char: inout Character)
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With