I would like to know how I can do the following please:-
// This is not correct
func += (inout lhs: Int, rhs: Int) -> Int {
return lhs + rhs
}
Objective Usage:- scrollTo(pageIndex: pageIndex += 1)
Your code is close, but it needs to do two things:
Your code only returns the new value, it does not update the left hand side value. In theory, you could use this:
func += (lhs: inout Int, rhs: Int) -> Int {
lhs = lhs + rhs
return lhs
}
But there is another problem; The standard += operator has a void
return type and you have defined a new operator with an Int
return type.
If you try and use the +=
operator in a context where a void return type is acceptable (which is the normal use of this operator) the compiler will give an ambiguity error, since it can't determine which function it should use:
someIndex += 1 // This will give an ambiguity compile time error
You can address this by defining the operator using generics, where the arguments conform to AdditiveArithmetic
(Thanks to @NewDev for this tip)
:
func +=<T: AdditiveArithmetic> (lhs: inout T, rhs: T) -> T {
lhs = lhs + rhs
return lhs
}
I must say, however, that this does seem like quite a lot of complexity to add, when you could simply have two lines of code; one to increment the pageIndex
and then a call to the function.