<< Back to SWIFT
Swift Loops: for, repeat and while Examples
Use the for-in loop and the enumerated method. See the while and repeat while loops.For-loop. Consider this river. The water is aquamarine. It moves around rock. It proceeds forward—in iterations it proceeds across the riverbed.
In a similar way we use a for-in loop to iterate forward. We repeat statements. We access indexes and elements with enumerated. While (and repeat while) are also used.
Example, for-in. This loop is a "for-each" loop. It acts upon a range or a collection like an array. Here we use a range of the numbers 0, 1, 2 and 3.
Underscore: If we do not need to access the iteration variable (like i), we can use an underscore instead of a proper name.
Swift program that uses for in, range
// Use a for-loop over the range.
// ... The range is inclusive so all numbers are included.
for i in 0...3 {
print(i)
}
// An underscore can be used in place of an identifier name.
for _ in 0...3 {
print("Hello")
}
Output
0
1
2
3
Hello
Hello
Hello
Hello
Exclusive bound. In Swift 4 the for-in loop is emphasized. Here we see the exclusive bound syntax, where we continue to one minus the maximum.
Tip: An exclusive maximum bound can help us avoid some awkward "minus one" expressions.
Swift program that uses exclusive bound
// Use exclusive maximum in for-loop.
for i in 0..<3 {
print("EXCLUSIVE LOOP:", i)
}
Output
EXCLUSIVE LOOP: 0
EXCLUSIVE LOOP: 1
EXCLUSIVE LOOP: 2
While. The for-loop gets most of the attention in programs. But "while" is also useful. It continues iterating while a condition evaluates to true.
Here: We begin the variable i at 5, and decrement it in each iteration of the while-loop. The loop stops when "i" is -1.
Decrement: This loop is a decrementing loop—it proceeds from 5 to 0. We must be careful to terminate the loop.
Swift program that uses while-loop
var i = 5
// Decrement i while it is greater than or equal to 0.
while i >= 0 {
print(i)
i -= 1
}
Output
5
4
3
2
1
0
Break. This program uses the break keyword in a while-loop to stop the loop. It tests for even numbers, and after 3 even numbers have been encountered, it breaks.
True: This is a while-true loop. We can use while "true" to continue a loop infinitely until a break (or return) is reached.
Modulo: We use a modulo division to test for even numbers. If a number is evenly divisible by 2, we know it is even.
IfSwift program that uses break
var i = 5
var evenCount = 0
// Break loop when the third even number is encountered.
while true {
if i % 2 == 0 {
print("Even")
evenCount += 1
if evenCount == 3 {
break
}
}
print(i)
i += 1
}
Output
5
Even
6
7
Even
8
9
Even
Continue. In a loop, the continue statement stops the current iteration, but does not terminate the entire loop. The next iteration is started.
Here: The program uses "continue" to avoid printing even numbers. Only odd numbers reach the print call.
Swift program that uses for-loop with continue
// Loop over the numbers 0 through 10.
for i in 0...10 {
// If number is even, continue to the next iteration.
if (i % 2) == 0 {
continue
}
// Print remaining numbers.
print(i)
}
Output
1
3
5
7
9
Enumerated. The enumerated() func can be used with a for-loop. A tuple of the index and value is returned for use in each iteration of the loop. Here we enumerate a String array.
String ArraySwift program that uses enumerated
let codes = ["XX", "XY", "YZ"]
// Loop over each index and value in the array.
for (index, value) in codes.enumerated() {
print("\(index) \(value)")
}
Output
0 XX
1 XY
2 YZ
Nested loop. For more complex algorithms, we can nest loops. In the inner block, we can access both the outer and the inner iteration variables.
Swift program that uses nested for-loop
// A for-loop can be nested.
for i in 0...2 {
for y in 0...2 {
// Access both iteration variables in inner block.
print("\(i), \(y)")
}
}
Output
0, 0
0, 1
0, 2
1, 0
1, 1
1, 2
2, 0
2, 1
2, 2
Repeat-while. This loop continues iterating over a block while the condition (specified after the block) is true. It is the same as a do-while loop in other languages like C.
RepeatTip: Sometimes a repeat-while loop can be a performance improvement. If the initial check is expensive and not needed, "repeat" is faster.
Swift program that uses repeat while loop
var size = 10
repeat {
// Increment.
size += 1
// Print the value.
print(size)
} while size < 16
Output
11
12
13
14
15
16
Range error. A range must go from low (the start index) to high (the end index). The short syntax does not support a decrementing range.
Swift program that causes range error
// This will not work: a range must go from low to high.
for i in 10...3 {
print(i)
}
Output
fatal error: Can't form Range with end < start
(lldb)
Adjacent elements. Here is a loop that accesses adjacent elements based on indexes. It uses enumerated() and ensures each index is the start of a pair.
Tip: A for-enumerated() loop is powerful. It can accommodate many requirements (like adjacent accesses).
Swift program that uses adjacent elements, for-loop
let positions = [10, 20, 30, 40, 50, 60]
// Loop over elements and indexes in array.
for (index, element) in positions.enumerated() {
// See if index is even and not the last index.
if index % 2 == 0 && index + 1 < positions.count {
// Get adjacent elements.
let next = positions[index + 1]
print("\(element), \(next)")
}
}
Output
10, 20
30, 40
50, 60
For C-style. In Swift 3 the C-style for-statement was removed. We must use enumerated() to iterate over the indexes and elements. A while-loop can also be a substitute.
Swift program that causes error
// This does not work in Swift 3.
for var i = 0; i < 4; i++ {
print(i)
}
Output
main.swift:2:1: C-style for statement has been removed in Swift 3
main.swift:2:24: '++' is unavailable: it has been removed in Swift 3
Loop over string chars. To loop over the characters in a string, we must use indexes. We start at startIndex and stop when endIndex is reached. We cannot just access chars with Ints.
EndIndex, String For-Loop
A summary. Loops are important in most programs. And most of the time spent in programs is spent in loops. This is a good focus for optimization efforts.
Related Links:
- Swift String Append Example: reserveCapacity
- Swift File (Read Text File Into String)
- Swift Find Strings: range of Example
- Swift Subscript Example
- Swift hasPrefix and hasSuffix Examples
- Swift Array of Dictionary Elements
- Swift Tutorial
- Swift Odd and Even Numbers
- Swift Operator: Equality, Prefix and Postfix
- Swift Dictionary Examples
- Swift Class Example: init, self
- Swift Combine Arrays: append, contentsOf
- Swift Initialize Array
- Swift Int Examples: Int.max, Int.min
- Swift 2D Array Examples
- Swift Error Handling: try, catch
- Swift Repeat While Loop
- Swift Optional: Nil Examples
- Swift Replace String Example
- Swift Print: Lines, Separator and Terminator
- Swift inout Keyword: Func Example
- Swift Lower, Uppercase and Capitalized Strings
- Swift enum Examples: case, rawValue
- Swift Padding String Example (toLength)
- Swift UIActivityIndicatorView Example
- Swift UIAlertController: Message Box, Dialog Example
- Swift UIButton, iOS Example
- Swift UICollectionView Tutorial
- Swift UIColor iOS Example: backgroundColor, textColor
- Swift UIFont Example: Name and Size
- Swift UIImageView Example
- Swift UIKit (Index)
- Swift UILabel Tutorial: iPhone App, Uses ViewController
- Swift String
- Swift Remove Duplicates From Array
- Swift If, If Else Example
- Swift Caesar Cipher
- Swift UIStepper Usage
- Swift UISwitch: ViewController
- Swift UITableView Example: UITableViewDataSource
- Swift UITextField: iPhone Text Field Example
- Swift UITextView Example
- Swift UIToolbar Tutorial: UIBarButtonItem
- Swift UIWebView: LoadHtmlString Example
- Swift Var Versus Let Keywords
- Swift Math: abs, sqrt and pow
- Swift Reverse String
- Swift Struct (Class Versus Struct)
- Top 22 Swift Interview Questions (2021)
- Swift Substring Examples
- Swift Switch Statements
- Swift Convert Int to Character: UnicodeScalar, utf8
- Swift Property Examples
- Swift isEmpty String (characters.count Is Zero)
- Swift Recursion
- Swift ROT13 Func
- Swift Convert String to Byte Array: utf8 and UInt8
- Swift Keywords
- Swift Convert String to Int Example
- Swift Join Strings: joined, separator Examples
- Swift String Literal, Interpolation
- Swift Extension Methods: String, Int Extensions
- Swift Characters: String Examples
- Swift Func Examples: Var, Return and Static
- Swift Guard Example: Guard Else, Return
- Swift Fibonacci Numbers
- Swift Trim Strings
- Swift Set Collection: Insert and Contains
- Swift Tuple Examples
- Swift Loops: for, repeat and while Examples
- Swift Split Strings Example (components)
- Swift Array Examples, String Arrays
- Swift UIPickerView Example: UIPickerViewDataSource
- Swift UIProgressView Example: Progress
- Swift UISegmentedControl
- Swift UISlider Example
- Swift Random Numbers: arc4random
- Swift ASCII Table
- Swift Range Examples (index, offsetBy)
- Swift String Length
- Swift Sort String Arrays: Closure Examples
Related Links
Adjectives
Ado
Ai
Android
Angular
Antonyms
Apache
Articles
Asp
Autocad
Automata
Aws
Azure
Basic
Binary
Bitcoin
Blockchain
C
Cassandra
Change
Coa
Computer
Control
Cpp
Create
Creating
C-Sharp
Cyber
Daa
Data
Dbms
Deletion
Devops
Difference
Discrete
Es6
Ethical
Examples
Features
Firebase
Flutter
Fs
Git
Go
Hbase
History
Hive
Hiveql
How
Html
Idioms
Insertion
Installing
Ios
Java
Joomla
Js
Kafka
Kali
Laravel
Logical
Machine
Matlab
Matrix
Mongodb
Mysql
One
Opencv
Oracle
Ordering
Os
Pandas
Php
Pig
Pl
Postgresql
Powershell
Prepositions
Program
Python
React
Ruby
Scala
Selecting
Selenium
Sentence
Seo
Sharepoint
Software
Spellings
Spotting
Spring
Sql
Sqlite
Sqoop
Svn
Swift
Synonyms
Talend
Testng
Types
Uml
Unity
Vbnet
Verbal
Webdriver
What
Wpf