Stefan
Stefan

Reputation: 936

Elements appended to array return nil

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?

Upvotes: 0

Views: 266

Answers (2)

Charles Srstka
Charles Srstka

Reputation: 17060

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.

Upvotes: 2

carlito
carlito

Reputation: 64

You've forgot to initialise the arrays

Try adding

evenImages = []
oddImages = []

before your for loop

Upvotes: 1

Related Questions