Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Shift Swift Array

Tags:

arrays

ios

swift

Array of Colors

let colorArray = [
    UIColor.redColor(),
    UIColor.orangeColor(),
    UIColor.yellowColor(),
    UIColor.greenColor(),
    UIColor.blueColor()
]

The goal is to shift the array:

  1. To start with a different color.
  2. To preserve the circular order of colors.

Example #1

If we wanted to start with the orange color (the color at index 1 in the original array), the array would look like this:

let colorArray = [
    UIColor.orangeColor(),
    UIColor.yellowColor(),
    UIColor.greenColor(),
    UIColor.blueColor(),
    UIColor.redColor(),
]

Example #2

If we wanted to start with the green color (the color at index 3 in the original array), the array would look like this:

let colorArray = [
    UIColor.greenColor(),
    UIColor.blueColor(),
    UIColor.redColor(),
    UIColor.orangeColor(),
    UIColor.yellowColor()
]
like image 701
Zelko Avatar asked Jul 22 '15 05:07

Zelko


People also ask

Are arrays in Swift dynamic?

Swift arrays come in two flavors: dynamic and static.

What is a Swift array?

Swift is a type inference language that is, it can automatically identify the data type of an array based on its values. Hence, we can create arrays without specifying the data type. For example, var numbers = [2, 4, 6, 8] print("Array: \(numbers)") // [2, 4, 6, 8]


1 Answers

I know this might be late. But the easiest way to rotate or shift an array is

func shifter(shiftIndex: Int) {
   let strArr: [String] = ["a","b","c","d"]
   var newArr = strArr[shiftIndex..<strArr.count]
   newArr += strArr[0..<shiftIndex]       
   println(newArr)  }

shifter(2) //[c, d, a, b] you can modify the function to take array as input
like image 148
zizutg Avatar answered Oct 27 '22 18:10

zizutg