-1

I have an array of 6 different colors:

var colorList: [String] = ["blue", "green", "purple", "red", "yellow", "orange"]

and I am trying to create a function that shifts each element by one to the right like so:

["orange", "blue", "green", "purple", "red", "yellow"]

How do I go about doing this?

rmaddy
  • 314,917
  • 42
  • 532
  • 579
Jimmy Lee
  • 215
  • 2
  • 12

1 Answers1

5
colorList.insert(colorList.popLast()!, atIndex: 0)

or as an extension on Array

extension Array {
    mutating func shiftRight() {
        if let obj = self.popLast(){
            self.insert(obj, atIndex: 0)
        }
    }
}

var colorList: [String] = ["blue", "green", "purple", "red", "yellow", "orange"]
colorList.shiftRight()
print(colorList)

results in

["orange", "blue", "green", "purple", "red", "yellow"]
vikingosegundo
  • 52,040
  • 14
  • 137
  • 178
  • 1
    @downvoter: please explain why this answer deserves a down vote. – vikingosegundo Sep 10 '16 at 17:02
  • instead of answering a duplicate, you should downvote to avoid other duplicate question from being posted, i have revoked my downvote, also – Mr. Xcoder Sep 10 '16 at 17:35
  • When I answered it wasn't closed as a duplicate – otherwise I wouldn't be able to post it. And I am not aware that I am obligated to search for duplicates prior answering. – vikingosegundo Sep 10 '16 at 17:37
  • ok, but just pointed that... no offence – Mr. Xcoder Sep 10 '16 at 17:38
  • I don't follow meta, so this is just my opinion... I generally don't think answers should be downvoted for any issue related to the question. – Kenneth Ito Sep 10 '16 at 17:49
  • @KennethIto I have revoked my downvote! – Mr. Xcoder Sep 10 '16 at 17:51
  • There is a situation where it makes sense to down vote questions in respect to a question closed as a duplicate: when the answer is written by someone who participated in the closure, as this gives an unfair advantage to the answerer. http://stackoverflow.com/questions/39379858/xcode-8-and-ipod-touch/39380216#39380216 – vikingosegundo Sep 11 '16 at 01:10
  • Swift 5 solution should be. `mutating func shiftRight() { if let last = self.popLast() { insert(last, at: 0) } }` – muhasturk May 16 '20 at 23:10