0

I am new to learning Swift and am trying to solve a challenge in Swift Programming: The Big Nerd Ranch Guide (1st Ed.). The question is in Chapter 6 about using a nested loop:

Use a loop to count by 2 from 0 to 100. Use another loop to make sure the first loop is run 5 times. Hint: one good way to do this is to use a nested loop.

I think I've found the answers but a bit unsure, any advise would be much appreciated!

for i in 1...5 {
    for i in 0...100 {
        if i % 2 == 0 {
            print(i)
        }
    }
}
9
  • 1
    I would avoid using the same index variable, i, for both loops. That is confusing. Commented Sep 22, 2018 at 11:34
  • 1
    @Carpsen90: Not that I would recommend it, but you can have nested loops with the same name for the loop variable, the inner i then simply shadows the outer i. Commented Sep 22, 2018 at 12:16
  • @MartinR Good to know 👍🏻 Commented Sep 22, 2018 at 12:18
  • @Carpsen90 Because the question asks for the counts to be repeated 5 times so I thought the solution would be to nest the loop inside another that will make it run 5 times. Commented Sep 22, 2018 at 12:37
  • @delb99 If the goal is count from 0 to 100, using nested loops, with the outside loop running 5 times, then see my answer. If you want to count from 0 to a 100 five times then your code already works and you should take the comments from Duncan and Martin into consideration. Commented Sep 22, 2018 at 12:42

1 Answer 1

2

Basically the solution is correct. However in Swift there are two more efficient syntaxes

  1. Filter with where

    for _ in 1...5 {
        for i in 0...100 where i % 2 == 0 {
            print(i)
        }
    }
    
  2. Loop with stride (recommended)

    for _ in 1...5 {
        for i in stride(from: 0, through: 100, by: 2) {
            print(i)
        }
    }
    

As the outer index variable is not used follow the replacing with '_' suggestion in the warning

Sign up to request clarification or add additional context in comments.

2 Comments

I haven't seen the where qualifier on a for loop before. Where did you learn that? (Voted)
@DuncanC It's listed in Swift - Summary of the Grammar. The where clause is a common pattern in Swift. It can be used in for loops, switch cases, generics and as type constraint operator.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.