Question about Challange 5 in "Swift Tutorial for Beginners" - what's the use of nested loop?

Hello. I’m trying to learn Swift. I’m now on lesson 5 of “Swift Tutorial for Beginners”. I’m finishing all the challanges, but I’m stuck at Challange 5. I don’t get why should I use nested loop.

According to the shared files, the code should look like this:

var drawPixel:String = "*"
var height:Int = 5
var tempRow:String = ""

for columnPixel in 1...height {
    tempRow = ""
    for _ in 1...columnPixel{
        tempRow += drawPixel
    }
    print(tempRow)
}

but

var drawPixel:String = "X"
var height:Int = 5
var tempRow:String = "Example"

for _ in 1...height{
    tempRow += drawPixel
    print(tempRow)
}

also works the way it should and seems way simplier. So what’s the benefit of using nested loop? I understand my method, but not the one I’m supposed to use - would appreciate a simple clarification. :slight_smile:

Thank you in advance,
Kacper

As the old saying goes “There is more than one way to skin a cat”.

The exercise is to get you to understand how nested loops work. Yes you can achieve the result in the way you have done it and if you are already comfortable with nested loops then great.

The thing is, I’m not really sure what’s the difference between your code and mine. I don’t get “nested loops” - could you explain why you used it in this example? Or do you have any tutorial covering nested loops? Unfortunately it’s not in lesson 5

Firstly can I just clarify that I am not the CodeWithChris guy. I just happen to have the same first name as Chris Ching and I am a moderator in this site.

There are situations where nested loops are required. I have used them in SpriteKit applications where game setup might have a layout that has columns and rows so in that scenario you would have an outer loop controlling the rows and an inner loop controlling the columns.

For example, in this game you have 3 rows of playing cards face down and your task is to match pairs of cards. Here is a screen shot:

So the layout in this case requires a nested loop.