Search code examples
iosswiftuikituicolor

Random number corresponding to array of UIColors- ERROR


I have a function that creates a CGRect and I am trying to assign a random color to each of them.

I create the colors as variables with the type UIColor and then put them into an array called colors. Then, I create a random number generator and call it when defining the background color of the CGRect, but I get the error:

Cannot call value of non-function type "[UIColor}"

Why is this? Here is my code:

func addBox(location: CGRect) -> UIView {
    let newBox = UIView(frame: location)

    let red = UIColor(red: (242.0/255.0), green: (186.0/255.0), blue: (201.0/255.0), alpha: 1.0)
    let green = UIColor(red: (186.0/255.0), green: (242.0/255.0), blue: (216.0/255.0), alpha: 1.0)
    let yellow = UIColor(red: (242.0/255.0), green: (226.0/255.0), blue: (186.0/255.0), alpha: 1.0)
    let blue = UIColor(red: (186.0/255.0), green: (216.0/255.0), blue: (242.0/255.0), alpha: 1.0)
    let colors = [red, green, yellow, blue]
    let randomNum:UInt32 = arc4random_uniform(4)

    newBox.backgroundColor = UIColor(colors(randomNum))

    hView.insertSubview(newBox, at: 0)
    return newBox
}

If anyone could solve this that would be amazing. Any help would be immensely appreciated!! Thanks a ton in advance.


Solution

  • This:

    newBox.backgroundColor = UIColor(colors(randomNum))
    

    should be:

    newBox.backgroundColor = colors[randomNum]
    

    colors is an array of UIColor. You just need one element from the array.

    You should also change:

    let randomNum:UInt32 = arc4random_uniform(4)
    

    to:

    let randomNum = Int(arc4random_uniform(colors.count))
    

    This way if you add more colors to the array, you don't need to adjust this line. It makes your code less error prone.