CapeFurSeal
CapeFurSeal

Reputation: 183

Swift-iOS append a list of 3 image names, looped through count of an array of 6 repeated

I have 3 hard coded images in my swift project. "pollListBg1 to 3"

I have one array of my image strings e.g

var imageStringsArray: Array<String> = ["pollListBg1","pollListBg2","pollListBg3"]

and another array:

var stringsArray: Array<String> = ["String1","String2","String3","String4","String4","String6"]

I want to make a new array from the count of stringsArray which is 6 but with the image array imageStringsArray repeated:

e.g this is what my final array should look like:

var finalStringArray: Array<String> = ["pollListBg1","pollListBg2","pollListBg3","pollListBg1","pollListBg2","pollListBg3"]

I know how to run through a loop and append but I am a little confused:

var finalStringArray = [String]()
for (var i = 1; i <= 6; i++) {
let imageString = "pollListBg\(i).png"
finalStringArray.append(imageString)
}

Any help is much appreciated.

Upvotes: 0

Views: 526

Answers (1)

Fonix
Fonix

Reputation: 11597

havent tested this but might be what you are looking for

var finalStringArray = [String]()
for (var i = 0; i < stringsArray.count; i++) {

   let index = i % imageStringsArray.count + 1
   let imageString = "pollListBg\(index).png"
   finalStringArray.append(imageString)
}

or if you need to use the values from the array, try this

var finalStringArray = [String]()
for (var i = 0; i < stringsArray.count; i++) {

   let index = i % imageStringsArray.count
   let imageString = "\(imageStringsArray[index]).png"
   finalStringArray.append(imageString)
}

Upvotes: 1

Related Questions