I think this is one is fairly easy one since it has to do with simple logic, but I can't seem to figure it out. So I have two arrays:
1. An array of images
2. An array of imageViews
For simplicity sake, the number of images and imageviews will always be the same. What I want to do is for every image, assign it to a corresponding imageView in the same index in the imageView array. Here is my code... I was trying to use a for in structure, but I'm not sure if this is the right way to go. Any advice on this would be great! Thank you.
// progress elements are imageViews
// Assuming method is already been implemented after this declaration to specify
// the number of progressElements in the array
var progressElements = [UIImageView]()
// Assuming image1-4 have been declared already
var progressElementImages = [image1, image2, image3, image4]
// Method that accepts an array of UIImages and then assigned
func setProgressBarElement(images: [UIImage]) {
for element in progressElements {
element.image = images[???]
}
}
The simplest is to create a dictionary:
- you will be sure the 2 "arrays" match
- the for loop becomes very easy.
var imagesDico: [UIImageView:UIImage]
imagesDico = [image1: images[0], image2: images[1], image3: images[2], image4: images[3]]
for (element, image) in imagesDico {
element.image = image
}you could alos use zip:
for (element, image) in zip(progressElementImages, images) { // Creates the dictionary
element.image = image
}There is also a brute force solution :
func setProgressBarElement(images: [UIImage]) {
var index = 0
for element in progressElements {
element.image = images[index]
index += 1
}
}