I needed to be able to change the colour of my entire interface when the user tapped a button. My first design consisted of a series of labels that were easily referenced by outlets. Later I decided a Table View was a better fit – but how to retrospectively update the colours of the table cells?

Easy, I thought. I added an array of UITableViewCell to my ViewController class.

var theCells : [UITableViewCell]?

It had to be optional, I thought, because I could only add the cells as the table view was built thusly in my cellForRowAtIndexPath method.

return cell

The problem was when I later went to reference the array… it was nil! Crash!

After some noodling I suddenly got to thinking – what does .append( ) actually do for an array that doesn’t actually exist yet? Certainly it didn’t throw an error, but neither did it seem to add any elements. It kind of made sense – the array doesn’t exist yet, what do I append to?

The Apple documentation gave no real clues1 but a search eventually turned up this blog post which confirmed the optionality was indeed the issue and pointed out the rather obvious, in hindsight, solution.

Instead of an optional array, an empty array initialised right there in the declaration, thus avoiding the need to override init( ).

var cellRefs : [UITableViewCell] = []

Now the .append( ) does what I expect, the array is populated and a tap of my finger changes all the colours. Yay!

  1. A saying my father used seems once again appropriate at this juncture — “Road signs are put up by people who know where they’re going.”


Leave a Reply

Your email address will not be published. Required fields are marked *