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)
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:
But there is another problem; The standard += operator has a
void
return type and you have defined a new operator with anInt
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:You can address this by defining the operator using generics, where the arguments conform to
AdditiveArithmetic
(Thanks to @NewDev for this tip) :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.