Search code examples
swiftforeacharc4random

generate a random background color for each item in forEach loop


What I would like to do is see if its possible when in a for each loop that i can a assign a random background color to each item.I tried something below but that does not compile. I know there is a way to do this by setting a variable outside the for each and increasing as part of a uicolor but I want to see if there is a way to do this without creating a variable.

   var frontBox = UIButton()
var backBox = UIButton()


override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view.
    [frontBox,backBox,slider].forEach{
        $0.translatesAutoresizingMaskIntoConstraints = false
        view.addSubview($0)
        $0.backgroundColor = ar4random().uicolor
    }
    

}

Solution

  • Swift doesn't use ar4random anymore - to get a random number, you use .random(in: 0...1) or similar.

    Also, $0.backgroundColor takes in a UIColor, not a number. You are probably looking for something like this:

    $0.backgroundColor = UIColor(
        red: .random(in: 0...1),
        green: .random(in: 0...1),
        blue: .random(in: 0...1),
        alpha: 1
    )
    

    This composes a UIColor from red, green, and blue components, which are each a random number from 0 to 1.