Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

iOS

Control flow question

Let´s say I have got an array of different numbers like this

                       let numbers = [8, 2, 3, 4, 7, 9, 3, 4]

I want to use a for in loop that starts printing the number if number is lower than 5 and stops printing when the condition becomes false, never minding that the condition becomes true again later on.

The desired result of this example would therefore to be printing 2, 3 and 4.

How do i manage this?

I am not sure if I understand you correctly, as in your example nothing would be printed to the console whatsoever. The first int in your array is already greater than 5, so execution would be stopped right there. If 8 wasn't there 2, 3 and 4 would be the result, so I guess 8 is just there by mistake?

No 8 is there by intention. I want execution to start when a number is lower than 5 and stop when a number is higher than 5.

Got it, thanks ;)

1 Answer

Ok, the first thing that comes to my mind is the following:

let numbers = [8, 2, 3, 4, 7, 9, 3, 4]

var executionStarted = false

for number in numbers {
    if number < 5 {
        executionStarted = true
        print(number)
    } else {
        if executionStarted {
            break
        }
    }
}

Using a reusable function, this would look something like:

func getRangeFromArray(range: [Int], threshold: Int) -> [Int] {

    var result = [Int]()
    var executionStarted = false

    for number in range {
        if number < threshold {
            executionStarted = true
            result.append(number)
        } else {
            if executionStarted {
                break
            }
        }
    }
    return result
}

let numbers = [8, 2, 3, 4, 7, 9, 3, 4]
let range = getRangeFromArray(numbers, threshold: 5)

Please note there might be easier/better ways to do this, but that should work as a start.

Thanks!