0

I'm fairly certain on how to create an array of images using UIImage, but I cannot find any instructions on how to reference those array images with a for loop, my code attempts always produce an error that says uiimage is not convertible to int.

I want to iterate through the array, then display each image in sequence:

var imageArray: [UIImage] = [
UIImage(named: "image1.png")!,
UIImage(named: "image2.png")!
]
for element in enumerate(imageArray) {
imageLabel.image = (imageArray[element])
}

The idea being, a sequence of images will display on the iPhone (either automatically or by press of button).

I know this is incorrect code, but I wanted to give the gist of what I'm trying to do, I know there are better ways to do the same thing, but I'm trying to learn the limits and capabilities of swift code, and I do that by trying various ideas (good or bad) that come to my head as I learn each aspect of swift. Thanks in advance!

2 Answers 2

4

You're making things more difficult than they need to be. You can simply use for-in to get each image directly without worrying about its index:

for element in imageArray {
    imageLabel.image = element
}

enumerate(imageArray) returns tuples that contain the index of the elements paired with the element. You'd use it like this:

for (index, element) in enumerate(imageArray) {
    println("processing index \(index)")
    imageLabel.image = element
}
Sign up to request clarification or add additional context in comments.

Comments

1

Basically this is a for-in loop that iterates items stored in your array. The collection of items being iterated is of range from 0 (the first element) to the array's length as indicated by the use of the half-open range operator ..<
The value of element is set to the first number in the range (0), and the statements inside the loop are executed.

var imageArray: [UIImage] = [
    UIImage(named: "image1.png")!,
    UIImage(named: "image2.png")!
]

for element in 0..<imageArray.count {

   imageLabel.image = (imageArray[element])
}

P.S We want to use the half-open range operator because it contains its first value, but not its final value rather than the closed range operator (a...b) because then we would get an "Array index out of range" error.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.