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)

2

There are 2 best solutions below

7
On BEST ANSWER

Your code is close, but it needs to do two things:

  1. Add the right hand side to the left hand side
  2. Return the new value.

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.

0
On

I'm not sure if I understood you but, if I did i would be something like this

func nextPage(n1: Int) -> Int {

var number = n1 + 1 return number }