Constant definition within function lost

0

I have the following piece of code which gives me the error

"Use of unresolved identifier ‘randomcell’

But randomcell is clearly defined earlier on in the same function, why can the Else part not see it? I have tried redefining it inside the else part but it simply chooses another cell, I want to refer to the same random element in the second part of the function.

if seconds == 5 {
           let randomcell = viewArray.randomElement()
           randomcell?.backgroundColor = UIColor .red
           }
           else  {

               randomcell?.backgroundColor = UIColor .systemYellow
           }

Okay, I have been informed that defining the randomcell before the function will resolve the error which is does, however it does not get rid of larger problem which is that the second part of the function is moving on to a different cell, how do I keep track of a random element once it has been selected?

What is the definition of viewArray?

viewArray is defined inside the timer as

viewArray = [square1,square2,square3,square4,square5,square6,square7,square8,square9]

which is derivative of the initial definition - var viewArray = UIImageView
which stems from the 9 image views which are in a grid in the view.

If each of your square1, square2, square3… are a UIImageView in each case then the definition of viewArray should be:
var viewArray: [UIImageView]

so you would re-write viewArray = [square1,square2,square3,square4,square5,square6,square7,square8,square9] as
var viewArray: [UIImageView] = [square1,square2,square3,square4,square5,square6,square7,square8,square9]

1 Like