JunM
JunM

Reputation: 7150

For- in loop dynamic closed range

What is the correct way of having a dynamic close range of for-in loop? I got an error on this part for z in 1...[10-x]{

for x in 1...10{

    for y in 1...x{
        print(" ")
    }

    for z in 1...[10-x]{
        print("*")
    }

    println()

}

Error:

Playground execution failed: <EXPR>:26:15: error: 'ClosedInterval<T>' does not have a member named 'Generator' for z in 1...[10-x]{

Upvotes: 2

Views: 2114

Answers (1)

Martin R
Martin R

Reputation: 539795

[10-x] denotes an array (with the single element 10-x). You'll want "normal" parentheses:

for z in 1 ... (10 - x) { ... }

or just

for z in 1 ... 10 - x { ... }

because ... has a lower precedences than -.

As you noticed, this does not work for x = 10 because ranges with end < start are not allowed in Swift.

To execute a loop n times you better use the range 0 ..< n with the range operator that omits the upper value. This works for n = 0 as well:

for x in 1 ... 10 {
    for y in 0 ..< x {
        print(" ")
    }
    for z in 0 ..< 10 - x {
        print("*")
    }
    println()
}

Upvotes: 2

Related Questions