0

I have an array of UIImages I want split into two separate arrays, one containing objects whose index is even, and the other with objects whose index is odd.

Here's the code I'm using:

var evenImages: [UIImage]?
var oddImages: [UIImage]?

var imageArray: [UIImage]? {
    didSet{

        for z in 0..<((imageArray?.count)!) {
            if z % 2 == 0 {
                evenImages?.append(imageArray![z])
            } else {
                oddImages?.append(imageArray![z])
            }

            print(evenImages?.count) //prints nil
            print(oddImages?.count) //prints nil
        }
    }
}

The issue so far is that while the objects are seemingly being appended to the appropriate arrays, whenever I try to use them they are nil. Perhaps this is an issue with the order in which the variables are instantiated? Any thoughts?

2 Answers 2

2
evenImages?.append(imageArray![z])

What this line means is: "If evenImages is not nil, append imageArray![z] to it."

Unfortunately, if evenImages is nil, nothing will happen. And since it appears you never initialized it, this is going to be the case.

Later on:

print(evenImages?.count)

This means: "if evenImages is not nil, then print its count. Otherwise, just print nil." Unfortunately, evenImages is still nil, so you get nil.

Solution: evenImages doesn't need to be optional at all. Just initialize it to an empty array straight off:

var evenImages: [UIImage] = []
var oddImages: [UIImage] = []

Then you can get rid of all the ? marks when accessing it, and it'll never be nil.

Sidenote: I'd recommend also changing imageArray to be non-optional, and initializing it to an empty [] array as well. This way, you can get rid of the ugly (and crash-prone, if a nil happens to unexpectedly get in there somehow) ! when you append its components to your even and odd arrays.

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

Comments

1

You've forgot to initialise the arrays

Try adding

evenImages = []
oddImages = []

before your for loop

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.