Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift: ++ is deprecated - replaced code not working

Tags:

ios

swift

I know that "++" will be removed in Swift 3 and it has to be raplaced:

+= 1

but in this code, when I change to this value, I get error:

override func viewDidLoad() {
    super.viewDidLoad()

    imageView.image = images[index++]
    animateImageView()
}

When I insert:

imageView.image = images[index += 1]

I get error. How to change this code? This is image transition code (if I need, I'll pos whole code) and in Simulator everything works, but still, I would like to change it.

like image 459
Pejo Zmaj Avatar asked May 07 '16 00:05

Pejo Zmaj


2 Answers

As mentioned by dasblinkenlight the solution is to simply move the increment to be after you subscript the array.

Note the reason it is after because that is equivalent to have the postfix increment operator. If you were to use ++index then you would move the index += 1 to before the subscript.

A bit of extra info on whats going on here, If you imagine the operators as functions you can see what is going on here.

the ++ operator would have an implementation like this:

//++ declared as postfix operator before this.
func ++ (inout num: Int) -> Int {
  let temp = num
  num = num + 1
  return temp
}

where as the += operator is implemented like this:

func += (inout lhs: Int, rhs: Int) {
  lhs = lhs + rhs
}

The important thing to notice here is that the ++ operator returns an Int value that can be used within an subscript where as the += actually returns void (or returns nothing) and thus it cannot be used as an Int inside the subscript.

like image 171
Blake Lockley Avatar answered Oct 11 '22 12:10

Blake Lockley


Move += 1 out of the indexer, like this:

override func viewDidLoad() {
    super.viewDidLoad()
    imageView.image = images[index]
    index += 1
    animateImageView()
}
like image 41
Sergey Kalinichenko Avatar answered Oct 11 '22 14:10

Sergey Kalinichenko