Tommaso Pirola
Tommaso Pirola

Reputation: 33

How to assign a label to a random number (Swift)

I have 49 labels (from a1 to g7) and I want to randomly choose one of them. I set an array

let array = [a1, a2, ...., g6, g7]

And then the function to select the Random Label

let RandomGen = Int(arc4random_uniform(UInt32(array.count)))   

Once I chose the random label, how can I operate with it?
I want to change its background color, but if I write

RandomGen.backgroundColor = UIColor.green  

it shows this compile error Value of type 'String' has no member 'backgroundColor', because of course RandomGen is a variable, not a label.
How can I fix it?

Thank you.

Upvotes: 2

Views: 374

Answers (2)

Ahmad F
Ahmad F

Reputation: 31645

After generating (declaring) a random index for getting a label:

let randomElementIndex = Int(arc4random_uniform(UInt32(array.count)))

you could use it as follows:

let myRandomLabel = array[randomElementIndex]

assuming that myRandomLabel is a UILabel (since array is an array of UILabels), you could assign the desired background color for it:

// for instance:
myRandomLabel.backgroundColor = UIColor.black

Note that implementing:

RandomGen.backgroundColor = UIColor.green

is quite wrong, RandomGen is an Int which should be represents the random index, but not the label itself.

Upvotes: 0

Ozgur Vatansever
Ozgur Vatansever

Reputation: 52133

RandomGen is a number between 0 and array.count (from 0 to array.count - 1). You need to use that to get the label from the array and then change its background color:

array[RandomGen].backgroundColor = .green

Upvotes: 1

Related Questions