Reputation: 157
I currently have 2 view controllers. The first is an AVCaputureSession responsible for taking pictures. What I am looking to do is for every picture that I take and select the 'Yes' option, to add that image to my 'imageArray' and populate the second view controller, which contains 4 small imageViews.
The code below is what I have got for my second view controller, whereby I am trying to loop through my imageArray and set the images to the imageViews like that. It is crashing with this error:
fatal error: Array index out of range.
I don't know if there is a better way to do this?
if imageArray.count != 0 {
for im in 0..<imageArray.count {
imageViewArray[im].image = imageArray[im]
}
}
Upvotes: 0
Views: 35
Reputation: 154583
You are crashing because you have more images in imageArray
than imageViews in imageViewArray
. Using the min
value of the count
of both arrays will prevent your code from crashing, but you really need to decide what you want your app to do in the case that there are more images than imageViews:
if imageArray.count != 0 {
for im in 0..<min(imageArray.count, imageViewArray.count) {
imageViewArray[im].image = imageArray[im]
}
}
If you want to initialize your imageViews to the images in the imageArray
or to nil
if there aren't enough images in imageArray
for your imageViews, you can accomplish that in this way:
for (index, imageView) in imageViewArray.enumerate() {
imageView.image = (index < imageArray.count) ? imageArray[index] : nil
}
Upvotes: 2