Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Swift Loops and Control Transfer

Swift Loops and Control Transfer

Loops repeat the same block of code until an exit condition is met.

Swift provides three loop constructs—for-in, while, and repeat-while—along with break, continue, and labeled jump statements to control flow.

This article merges older, scattered content on for-in, while, repeat-while, break, and continue into one place and standardizes it on Swift 6 syntax.


The for-in Loop

for-in is the most commonly used loop in Swift, for iterating over sequences such as ranges, arrays, dictionaries, and strings.

Iterating Over Numeric Ranges

The closed range operator ... includes both endpoints, while the half-open range ..< does not include the right endpoint.

Example

import Foundation

// The closed range 1...5 yields 1, 2, 3, 4, 5 in order

for

i in

1

...

5

{

    print

(

"(i) times 5 equals (i * 5)"

)

}

The output of the above code is:



1 乘以 5 等于 5

2 乘以 5 等于 10

3 乘以 5 等于 15

4 乘以 5 等于 20

5 乘以 5 等于 25

Half-open range 0..<3 yields only 0, 1, 2, a form often used with array indices.

Example

import Foundation

// Half-open range 0..<3 does not include 3

for

i in

0

..

<

3

{

print

(

"runoob-(i)"

)

}

The output of the above code is:



runoob-0

runoob-1

runoob-2

Note:C-style for loops (writing initialization, condition, and increment as three semicolon-separated parts after for) were removed in Swift 3 and should no longer be used. When you need to loop with a fixed step, use a range plus stride(from:to:by:)。

Iterate over the array

Put an array after in, and the loop variable takes each element in turn.

Example

import Foundation

let sites

=

[

"Runoob"

,

"RUNOOB"

,

"www.runoob.com"

]

// site gets one array element each time

for

site in sites

{

    print

(

site

)

}

The output of the above code is:



Runoob

RUNOOB

www.runoob.com

Getting the Index with enumerated()

Calling enumerated() returns an "index + element" tuple, which can be split into two loop variables.

Example

import Foundation

let sites

=

[

"Runoob"

,

"RUNOOB"

,

"www.runoob.com"

]

// index starts at 0, so add 1 when displaying

for

(

index, site

)

in sites.

enumerated

(

)

{

    print

(

"(index + 1). (site)"

)

}

The output of the above code is:



1. Runoob

2. RUNOOB

3. www.runoob.com

Iterate over a dictionary

A dictionary's elements are "key + value" tuples, which can also be split into two loop variables.

But a dictionary is an unordered collection, and for-in iteration order is not guaranteed nor does it represent insertion order.

The example below sorts the keys before iterating so the output is deterministic.

Example

import Foundation

let ages

=

[

"Runoob"

:

10

,

"RUNOOB"

:

5

,

"Swift"

:

11

]

// Dictionary iteration order is not guaranteed; here output is sorted by key for easy comparison

for

(

key, value

)

in ages.

sorted

(

by

:

{

$

0

.

key

<

$

1

.

key

}

)

{

    print

(

"(key): (value)"

)

}

The output of the above code is:



RUNOOB: 5

Runoob: 10

Swift: 11

Uppercase letters have smaller Unicode values than lowercase ones, so RUNOOB comes before Runoob.

To iterate over only keys or values, use the keys and values view properties.

Example

import Foundation

let ages

=

[

"Runoob"

:

10

,

"RUNOOB"

:

5

,

"Swift"

:

11

]

print

(

ages.

keys

.

sorted

(

)

)

   

// Output after sorting keys

print

(

ages.

values

.

sorted

(

)

)

 

// Output after sorting values

The output of the above code is:



["RUNOOB", "Runoob", "Swift"]

[5, 10, 11]

Traverse a string

A string consists of characters and can be iterated character by character with for-in.

Example

import Foundation

for

ch in

"RUNOOB"

{

    print

(

ch, terminator

:

"-"

)

}

print

(

)

The output of the above code is:



R-U-N-O-O-B-

Filtering Elements with where

Append a where clause after in to run the loop body only for elements that satisfy the condition.

Example

import Foundation

// Only process numbers from 1 to 10 that are divisible by 3

for

i in

1

...

10

where i

%

3

==

0

{

    print

(

i

)

}

The output of the above code is:



3

6

9


stride(from:to:by:)

Use stride when you need to loop with a fixed step; it works with integers and floating-point numbers.

to excludes the endpoint, through includes it, and the step can be negative.

Example

import Foundation

// From 0 to 10, step 2, excluding 10

for

i in stride

(

from

:

0

, to

:

10

, by

:

2

)

{

    print

(

i, terminator

:

" "

)

}

print

(

)

// From 10 to 0, step -2, including 0

for

i in stride

(

from

:

10

, through

:

0

, by

:

2

)

{

    print

(

i, terminator

:

" "

)

}

print

(

)

// The step can also be a fraction

for

ratio in stride

(

from

:

0.0

, to

:

1.0

, by

:

0.25

)

{

    print

(

ratio, terminator

:

" "

)

}

print

(

)

The output of the above code is:



0 2 4 6 8

10 8 6 4 2 0

0.0 0.25 0.5 0.75


while loop

while checks the condition before each iteration and runs the loop body only when it is true.

The condition must be a Bool; Swift does not allow integers, strings, or optionals as conditions.

Example

import Foundation

var count

=

1

// Keep looping as long as count is less than or equal to 3

while

count

<=

3

{

    print

(

"Runoob (count)"

)

    count

=

1

 

// Increment with += 1; Swift has no ++ operator

}

The output of the above code is:



Runoob 1

Runoob 2

Runoob 3

Note:Swift has no ++ and -- operator; for increment and decrement, write += 1 The difference between -= 1。


The repeat-while Loop

repeat-while executes the loop body once, then checks the condition at the end.

Thus the loop body runs at least once, which suits scenarios of "do it once first, then decide whether to continue".

Example

import Foundation

var n

=

10

// Execute the loop body once, then check whether n < is less than 10

repeat

{

    print

(

"Executed at least once, n = (n)"

)

    n

=

1

}

while

n

<

10

The output of the above code is:



至少执行一次,n = 10

If you change it to while n < 10, because the condition is false from the start, the loop body never executes.

Loop syntax selection flowchart: choose for-in, while, or repeat-while based on whether the number of iterations is known; the lower part lists break, continue, and the scope of labeled break label and continue label


break and continue

break ends the entire loop immediately, while continue ends only the current iteration and moves directly to the next.

Example

import Foundation

for

i in

1

...

10

{

   

// Skip odd numbers for this iteration

   

if

i

%

2

!

=

0

{

       

continue

   

}

   

// End the whole loop when it exceeds 6

   

if

i

6

{

       

break

   

}

    print

(

i

)

}

The output of the above code is:



2

4

6


Labeled break and continue

In nested loops, a plain break only exits the innermost loop.

By labeling the outer loop, you can use break followed by the label to exit multiple levels at once.

break with a label

The example below ends the entire outer loop when i * j is greater than 4.

Example

import Foundation

// outer is the label for the outer for loop

outer

:

for

i in

1

...

3

{

   

for

j in

1

...

3

{

       

if

i

j

4

{

            print

(

"break outer at (i) x (j)"

)

           

break

outer  

// Exit two levels of loops at once

       

}

        print

(

"(i) x (j) = (i * j)"

)

   

}

}

The output of the above code is:



1 x 1 = 1

1 x 2 = 2

1 x 3 = 3

2 x 1 = 2

2 x 2 = 4

break outer 于 2 x 3

continue with a label

continue with a label skips the rest of the current outer-loop iteration and starts the next one directly.

Example

import Foundation

// row is the label for the outer for loop

row

:

for

i in

1

...

3

{

   

for

j in

1

...

3

{

       

if

j

==

2

{

           

continue

row  

// Skip the rest of the inner loop and go directly to the next outer iteration

       

}

        print

(

"(i)-(j)"

, terminator

:

" "

)

   

}

}

print

(

)

The output of the above code is:



1-1 2-1 3-1


Comparison of the Three Loops

Which loop to choose depends mainly on "whether the number of iterations is known" and "whether it must execute at least once".

Loop Applicable scenarios Feature
for-in Iterate over sequences such as ranges, arrays, dictionaries, and strings Iterations usually known, most concise syntax
while Iterations unknown, a condition decides whether to continue Checks the condition first, may execute zero times
repeat-while Executes at least once, then decides whether to continue Checks the condition last, body executes at least once
stride Iterate over numbers with a fixed step Step can be negative, and floating-point numbers are supported

Common questions

The following are the most frequently asked questions about loops and control transfer.

Why can't I write a C-style for loop?

The C-style three-part for was removed in Swift 3 and causes a compile-time error.

Use for i in 0.. instead

Why does dictionary iteration order differ each time?

A dictionary is an unordered collection and Swift promises no iteration order; this is by design, not a bug.

When you need a fixed order, sort the keys first or iterate over the result of sorted(by:).

Can a loop variable be modified inside the loop body?

No, a for-in loop variable is assigned at the start of each iteration and declared as a constant.

For a value you need to change while looping, declare a separate var outside the loop.

Why can't a while condition be 0 or an optional?

Swift conditions must be of type Bool; the integer 0, strings, and optionals cannot be used as conditions.

To check whether an optional has a value, use if let or compare with nil.