EDUCBA

EDUCBA

MENUMENU
  • Free Tutorials
  • Free Courses
  • Certification Courses
  • 600+ Courses All in One Bundle
  • Login
Home Software Development Software Development Tutorials Swift Tutorial Swift Loop
Secondary Sidebar
Swift Tutorial
  • Basics
    • How To Install Swift?
    • Swift Version
    • Swift Package Manager
    • Swift Operators
    • Swift Loop
    • Swift For Loop
    • Swift while loop
    • Swift do-while
    • Swift array
    • Swift Queue
    • Swift Dictionary
    • Swift forms
    • Swift sets
    • Swift map
    • Swift int to string
    • Swift Interview Questions
    • Swift extension
    • Swift guard
    • Swift enum
    • Swift zip
    • Swift?hashable
    • MVVM Swift

Related Courses

Swift Training Course

Windows Forms Training Course

Kali Linux Training

Swift Loop

By Anusua DuttaAnusua Dutta

Swift Loop

Definition of Swift Loop

Swift loop is part of swift programming language which comes into play when a situation arises where the same piece of code needs to be executed multiple times. In swift loop the statements get executed in the form of a sequence where the first statement gets executed first followed by the second statement and so on. Swift loop gives programmers the privilege to call and reuse the same sequence of statements any specified number of times. Swift loop works according to the sequence of conditional and control statements provided within the flow of loop.

Types of Loops in Swift

Types of loops in Swift with loop control statements are as follows :

  • While loop
  • For-in loop
  • Repeat…while loop / Do while loop
  • For-condition-increment loops
  • break statement
  • continue statement

1. While loop

While loop is the type of loop in swift programming language that is used for evaluating any condition of the statements or body within the loop to satisfy the condition as true and then making the entire loop executed successfully. If in case the condition_for_execution is false then the loop will not come inside the conditional_statements for the body of the code for execution.

Syntax :

Start Your Free Software Development Course

Web development, programming languages, Software testing & others

while (condition_for_execution)
{
Conditional_statements for the body of the code
}

Example 1: This program illustrates the while loop where a game of chess is played and if the condition is satisfied then the game is won as shown in the output.

Code:

import Foundation
import Glibc
var crrnt_lvl:Int = 1,
trgt_lvl:Int = 8
let check_mate = true
while (crrnt_lvl <= trgt_lvl) {
if check_mate {
print("Game is won \(crrnt_lvl)")
crrnt_lvl += 1
}
}
print("while_loop_outside.")

Output:

Swift Loop 1

2. For-in loop

for-in loop in a swift programming language is used for iterating over the set of data structures like array and dictionary which have some sequence and order to follow and walkthrough. The elements present in the array or dictionary need to be in proper arrangement.

Syntax

for index_with_sequence
{
statements for the body of the code
}

Example 2: This program illustrates the for-in loop in swift programming language which is used for iterating over the list of arrays with vehicle name for getting the number of tires present within the vehicles as shown in the output.

Code:

import Foundation
import Glibc
let no_of_tyres = ["car": 4, "truck": 6, "bike": 2] for (vehicle_nm, tyre_cnt) in no_of_tyres
{
print("\(vehicle_nm)s that consists of \(tyre_cnt) tyres.")
}

Output:

Swift Loop 2

3. Repeat…while loop or do-while loop

Repeat while loop or do while loop behaves in a way that whichever statement is present within the body with the conditional statement will get executed at least once in the entire execution. More important focus area is the termination condition which it tests for once in the entire search at the time of execution of the statements in an increment manner. Loop execution continues until execution of statement becomes false.

All in One Software Development Bundle(600+ Courses, 50+ projects)
Python TutorialC SharpJavaJavaScript
C Plus PlusSoftware TestingSQLKali Linux
Price
View Courses
600+ Online Courses | 50+ projects | 3000+ Hours | Verifiable Certificates | Lifetime Access
4.6 (86,697 ratings)

Syntax:

repeat
{
Statements_to_satisfy_body
}
while (conditional_statements)

Example 3: This program illustrates the repeat while loop where a game like snake and ladder is played where there is a scenario to repeat the conditional statements within the board game to make the entire game a win situation with the condition as shown in the output.

Code:

import Foundation
import Glibc
let finl_sqr = 36
var brd_gm = [Int](repeating: 0, count: finl_sqr + 1)
brd_gm[05] = +12; brd_gm[08] = +11; brd_gm[10] = +09; brd_gm[12] = +02
brd_gm[20] = -05; brd_gm[22] = -13; brd_gm[24] = -02; brd_gm[28] = -09
var sqr = 0
var dc_rll = 0
repeat
{
sqr += brd_gm[sqr] dc_rll += 1
if dc_rll == 12 { dc_rll = 1 }
sqr += dc_rll
} while sqr < finl_sqr
print("Game_Won!")

Output:

Swift Loop 3

4. For-condition-increment Loops

There is not much difference in for-condition-increment loops in Swift programming language as compared to C programming language. The entire loop consists of an initialization phase followed by a test of the condition, increment with the statement, and then to execute every iteration of the loop.

Syntax:

For initialization_vl; condition; increment++
{
Conditional_statements_for_body
}

Example 4: This program illustrates the for-condition-increment loops in swift with version 4.0 which uses stride to give the same feature as for-condition-increment in Swift 3 versions and below as they are now obsolete for more requirements thus the features are deprecated to give the same output as shown below.

Code:

import Foundation
import Glibc
for indx in stride(from: 0, to: 8, by: 6)
{
print(indx)
}

Output:

Swift Loop 4

5. Break Statement

Whenever the situation is to come out of the running program without waiting to get a termination till the end of execution gives break statement the push and ability to be used frequently. In actual terms, break statement is mostly used for encountering a loop inside the body. The loop gets terminated at one go when the program control calls for break as soon as possible and will resume at the next statement in the following loop.

Syntax:

Switch statement {
Case 1 :
Case 2 :
.
.
.
Case n:
Default :
Break;
}
Print statement
{
Statement;
}

Example 5: This program demonstrates the break statement as part of swift loop which gives the value once the execution is completed as shown in the output.

Code:

import Foundation
import Glibc
let nm_symbl: Character = "X"
var psbl_int_val: Int?
switch nm_symbl {
case "1", "X":
psbl_int_val = 1
case "2", "X":
psbl_int_val = 2
case "3", "X":
psbl_int_val = 3
case "4", "X":
psbl_int_val = 4
default:
break
}
if let int_val = psbl_int_val {
print("The int_value_comes \(nm_symbl) out to be \(int_val).")
} else {
print("the int_value_cannot come out for. \(nm_symbl).")
}

Output:

Swift Loop 5

6. Continue Statement

Continue statement keeps a check on the iteration statement to keep the loop with a check whether to stop or start the execution once the start after the beginning of the loop is performed.

Syntax:

Case 1 : Stmnt_1;
Case 2 : Stmnt_2;
.
.
.
.
Case 3 : Stmnt_3;
Default: continue
{
Print()
}

Example 6: This program demonstrates the continue statement which instructs to continue the flow till the next iteration is made as shown in the output by removing the characters that are not needed.

Code:

import Foundation
import Glibc
let pzl_inpt = "hope_all_is_good"
var pzl_otpt = ""
let Remv_chrcters: [Character] = ["e", "h", "s", "g", "d", " "] for Charc_incl in pzl_inpt {
if Remv_chrcters.contains(Charc_incl) {
continue
}
pzl_otpt.append(Charc_incl)
}
print(pzl_otpt)

Output:

example 6

Conclusion

Swift loop is a looping pattern which is mostly performed in order to perform reusability of code especially for not to perform repetition of same components. All the iteration within the array, dictionary with a specified count, and sequence is performed using swift loop which provides many more features like flexibility, robustness, and versatility by removing the redundancy within the codebase.

Recommended Articles

This is a guide to Swift Loop. Here we discuss the definition and Types of Loops in Swift and examples with code implementation. You can also go through our other related articles to learn more –

  1. Swift For Loop
  2. Swift Version
  3. Properties in Swift
  4. What is Swift?
Popular Course in this category
Swift Training (10 Courses, 11+ Projects)
  10 Online Courses |  11 Hands-on Projects |  63+ Hours |  Verifiable Certificate of Completion
4.5
Price

View Course

Related Courses

Windows Forms Training (4 Courses, 3+ Projects)4.9
Kali Linux Training (3 Courses, 3+ Projects)4.8
0 Shares
Share
Tweet
Share
Primary Sidebar
Footer
About Us
  • Blog
  • Who is EDUCBA?
  • Sign Up
  • Live Classes
  • Corporate Training
  • Certificate from Top Institutions
  • Contact Us
  • Verifiable Certificate
  • Reviews
  • Terms and Conditions
  • Privacy Policy
  •  
Apps
  • iPhone & iPad
  • Android
Resources
  • Free Courses
  • Java Tutorials
  • Python Tutorials
  • All Tutorials
Certification Courses
  • All Courses
  • Software Development Course - All in One Bundle
  • Become a Python Developer
  • Java Course
  • Become a Selenium Automation Tester
  • Become an IoT Developer
  • ASP.NET Course
  • VB.NET Course
  • PHP Course

ISO 10004:2018 & ISO 9001:2015 Certified

© 2022 - EDUCBA. ALL RIGHTS RESERVED. THE CERTIFICATION NAMES ARE THE TRADEMARKS OF THEIR RESPECTIVE OWNERS.

EDUCBA
Free Software Development Course

C# Programming, Conditional Constructs, Loops, Arrays, OOPS Concept

*Please provide your correct email id. Login details for this Free course will be emailed to you

By signing up, you agree to our Terms of Use and Privacy Policy.

EDUCBA Login

Forgot Password?

By signing up, you agree to our Terms of Use and Privacy Policy.

EDUCBA
Free Software Development Course

Web development, programming languages, Software testing & others

*Please provide your correct email id. Login details for this Free course will be emailed to you

By signing up, you agree to our Terms of Use and Privacy Policy.

EDUCBA

*Please provide your correct email id. Login details for this Free course will be emailed to you

By signing up, you agree to our Terms of Use and Privacy Policy.

Let’s Get Started

By signing up, you agree to our Terms of Use and Privacy Policy.

This website or its third-party tools use cookies, which are necessary to its functioning and required to achieve the purposes illustrated in the cookie policy. By closing this banner, scrolling this page, clicking a link or continuing to browse otherwise, you agree to our Privacy Policy

Loading . . .
Quiz
Question:

Answer:

Quiz Result
Total QuestionsCorrect AnswersWrong AnswersPercentage

Explore 1000+ varieties of Mock tests View more