Move to next element in array every time it calls the function Swift 3

Get index of current Image from array and increment 1. If array indices doesn't contains next image index use 0th image. If imageview doesn't have any images show 0th image. Try this.

func nextImage()
  {
    let currentIndex = arrayPhoto.index(of: imageView.image ?? UIImage()) ?? -1
    var nextIndex = currentIndex+1
    nextIndex = arrayPhoto.indices.contains(nextIndex) ? nextIndex : 0
    imageView.image = arrayPhoto[nextIndex]
  }

My solution on Swift 4.2:

Next element:

let currentIndex = songPlaylist.index(of: selectedSong ?? Song()) ?? -1
var nextIndex = currentIndex + 1
nextIndex = songPlaylist.indices.contains(nextIndex) ? nextIndex : 0
selectedSong = songPlaylist[nextIndex]

Previous element:

let currentIndex = songPlaylist.index(of: selectedSong ?? Song()) ?? -1
var nextIndex = currentIndex - 1
nextIndex = songPlaylist.indices.contains(nextIndex) ? nextIndex : songPlaylist.count - 1
selectedSong = songPlaylist[nextIndex]

Tags:

Arrays

Ios

Swift