3

I have an array of 4 UIImageVIew and array of images of variable size: [UIImage].

I would like to iterate through the array of views and assign 4 last images to each view.

let photos = images.suffix(4)
for (index, view) in views.enumerate() {
  if index <= photos.count - 1 {
    view.image = photos[index]
  } else {
    view.image = nil
  }
}

Code works perfectly if there are no more than 4 elements in images. Then I got a crash: fatal error: ArraySlice index out of range.

I printed out index in for-loop and it seems that crash happens when index is 0. views.count and photos.count return 4 in the same loop.

So, I get an error when accessing the first - 0 element of an non-empty array.

In Swift 1.2 this code worked flawlessly:

let photos = suffix(images, 4)
for (index, view) in enumerate(views) {
  if index <= photos.count - 1 {
    view.image = photos[index]
  } else {
    view.image = nil
  }
}

The only change after switching to 2.0 is in suffix and enumerate methods.

Does it look like a Swift 2.0 bug or am I doing something wrong? Link to source file

Solution I've finished with:

let photos = Array(images.suffix(4))

Should work exactly as suffix() function in Swift 1.2

2
  • Hi I think re-implement suffix is unnecessary. Just create a new array with the slice passed in the initializer would do the trick. As swift structs is copy-on-write. so there is no performance or memory penalty. Commented Sep 11, 2015 at 3:15
  • Fujia, good solution! Updated the question. Commented Sep 14, 2015 at 14:39

1 Answer 1

5

This is due to a recent change to ArraySlice. Now indices of ArraySlice are not zero-based. For example, if images.count == 10, then images.suffix(4).startIndex == 5. See the release note here, and search for the words “For consistency and better composition of generic code”.

Sign up to request clarification or add additional context in comments.

3 Comments

Thank you! Any quick-fix to ArraySlice to make it again zero-based?
@RichardTopchiy Probably wrap the suffix slice in a new array, or 'photos[index + photos.startIndex]', I replied this on the train, not tested.
Good point! I've just re-implemented suffix() function from scratch

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.