Group Group Group Group Group Group Group Group Group

Use a nested for loop to print the items of arrays on buttons

I wanted to use a nested for loop to display the names of array names on each of the buttons in the for loop. I want to do everything in one loop. Right now my code works but the only name being printed is clear and its on every button. The buttons should go one pen etc. You can assume all of the items are buttons.

     let names = ["line", "pen", "graph","save","nxt","opacityBtn","strokeSize","undo","clear"]
    var increase = 0.1
    for b in [line, pen, graph,save,nxt,opacityBtn,strokeSize,undo,clear] {
        b.backgroundColor = UIColor.init(red: CGFloat(increase), green: 0.2, blue: 0.2, alpha: 1)
        increase += 0.10
        b.layer.borderWidth = 1
        
        for i in names{
            b.setTitle(i, for: .normal)
        }
     
    }

Hi Tim,
That happens because for each button you are looping through all the names and setting the title to be the last name inside your name array.

As you have the same amount of names and buttons, you do not need a nested loop, you could track with index you are inside the loop and access the names array directly.

You could do something like this.

    let names = ["line", "pen", "graph", "save", "nxt", "opacityBtn", "strokeSize", "undo", "clear"]
    let buttons = [line, pen, graph, save, nxt, opacityBtn, strokeSize, undo, clear]
    var increase = 0.1
    for index in 0..<buttons.count {
        let b = buttons[index]
        b.backgroundColor = UIColor.init(red: CGFloat(increase), green: 0.2, blue: 0.2, alpha: 1)
        increase += 0.10
        b.layer.borderWidth = 1
        b.setTitle(names[index], for: .normal)
    }