This is the sample code from swift documentation. I am learning swift language, and I saw the functiontype as parameter, The sample code does not have inout keyword. But I am trying to use this with inout paramter, but the below sample is not working as expected.
https://docs.swift.org/swift-book/LanguageGuide/Functions.html (Function Types as Return Types)
//Function Types as Return Types
func stepForward(_ input: inout Int) -> Int {
return input + 1
}
func stepBackward(_ input: inout Int) -> Int {
return input - 1
}
func chooseStepFunction(backward: Bool) -> (inout Int) -> Int {
let a = backward ? stepBackward : stepForward
return a
}
var currentValue = 3
let moveNearerToZero = chooseStepFunction(backward: currentValue > 0)
print(moveNearerToZero(¤tValue))
print(currentValue)
Actual output 2 3
Expected output 2 2
Because CurrentValue is inout paramter. Passing the currentValue as 3 initially prints value 2 using stepBackward() method
and I want to maintain the value after the decrement.
But the currentValue is not maintained here.
Defining and Calling Functions. When you define a function, you can optionally define one or more named, typed values that the function takes as input, known as parameters. You can also optionally define a type of value that the function will pass back as output when it's done, known as its return type.
If you want a function to modify a parameter's value, and you want those changes to persist after the function call has ended, define that parameter as an in-out parameter instead.
Swift Function Return Values A function may or may not return value. If we want our function to return some value, we use the return statement and return type. For example, func addNumbers(a: Int, b: Int) -> Int { var sum = a + b return sum } let result = addNumbers(a: 2, b: 3) print("Sum:", result) Output Sum: 5.
That's because you are not actually assigning value to parameter after applying arithmetics you are just returning new value without assigning it. Try the following code
//Function Types as Return Types
func stepForward(_ input: inout Int) -> Int {
input += 1
return input
}
func stepBackward(_ input: inout Int) -> Int {
input -= 1
return input
}
func chooseStepFunction(backward: Bool) -> (inout Int) -> Int {
let a = backward ? stepBackward : stepForward
return a
}
var currentValue = 3
let moveNearerToZero = chooseStepFunction(backward: currentValue > 0)
print(moveNearerToZero(¤tValue))
print(currentValue)
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