Swift – Comments

Swift – Comments ”; Previous Next Comments are the special text in the programs that are not compiled by the compiler. The main agenda of the comments is to explain to us what is happening in the specific line of code or in the whole program. Programmers generally add comments to explain the line of codes in the program. Or we can say that comments are non-executable text and they are like a note or reminder to the user or programmer. In Swift, we can define comments in three different ways − Single line comments Multi-line comments Nested Multi-line comments Single Line Comment in Swift A single-line comment is used to add only one-liner text in the code. A single-line comment begins with double forward slashes (//). The compiler or interpreter always ignores them and does not affect the execution of the program. Syntax Following is the syntax of single line comment − // Add your comment here Example Swift program to add a single-line comment. Here we add a single-line comment in the program to explain the working of the for-in loop. import Foundation let num = 7 let endNum = 10 // For loop to display a sequence of numbers for x in num…endNum{ print(x) } Output 7 8 9 10 Multi-Line Comment in Swift Multi-line comments are used to display multiple lines of non-executable text in the program to explain the working to the specific line of code or to add warnings, notes, etc. by the developers. Like other programming languages, in Swift, the multi-line comments begin with a forward slash followed by an asterisk(/*) and end with an asterisk followed by the forward-slash (*/). Syntax Following is the syntax of multi-line comment − /* Add your Mult-line comment here */ Example Swift program to add multi-line comments. Here we add multiple lines of comment in the program to explain how to add two arrays of the same length. import Foundation let arr1 = [1, 4, 6, 2] let arr2 = [3, 5, 2, 4] var result = [Int]() /* Check the length of the array. If they are equal then we add them using the + operator and store the sum in the result array */ if arr1.count == arr2.count { for i in 0..<arr1.count { let sum = arr1[i] + arr2[i] result.append(sum) } print(result) } else { print(“Arrays must of same length.”) } Output [4, 9, 8, 6] Nested Multi-Line Comment in Swift Starting from Swift 4 a new feature is also included in the multi-line comment that is nested multi-line comment. Now you are allowed to nest or add a multi-line comment inside another multi-line comment. It can easily comment out many blocks, even if the block contains multi-line comments. Syntax Following is the syntax of nested multi-line comments − /* Add your multi-line comment. /* Add your nested multi-line comment. */ End multi-line comment */ Example Swift program to add nested multi-line comments. Here we add nested multiple lines of comment in the program to add an alternative code of adding two arrays. import Foundation let arr1 = [1, 4, 6, 2] let arr2 = [3, 5, 2, 4] var result = [Int]() /* Checks the length of the array. If they are equal then we add them using the + operator and store the sum in the result array /*You can also use the following code to add two arrays: if arr1.count == arr2.count { let result = zip(arr1, arr2).map(+) print(result) */ */ if arr1.count == arr2.count { for i in 0..<arr1.count { let sum = arr1[i] + arr2[i] result.append(sum) } print(result) } else { print(“Arrays must of same length.”) } Output [4, 9, 8, 6] Print Page Previous Next Advertisements ”;

Swift – Function Overloading

Swift – Function Overloading ”; Previous Next A Function is a snippet of code that is used to perform a specific task. In Swift, we are allowed to overload functions. Function overloading is a technique in which we can create multiple same-name functions but with different parameters or argument labels. So when an overloaded function is called, the compiler determines which function should execute according to the number of parameters and types of parameters provided at the time of call. In Swift, we cannot overload functions according to the return type. We can overload functions in the following ways − Overloading with a different number of parameters. Overloading with different parameter types. Overloading with argument label. Overloading with Different Number of Parameters In function overloading with a different number of parameters, the names of the two or more functions are the same but the number of parameters is different. The functions can have the same or different names of parameters. In this type of function overloading, the function is invoked according to the number of parameters provided by the user during the function call. Example Swift program to demonstrate function overloading with a different number of parameters. import Foundation // Function 1 func product(num1: Int, num2: Int){ // Calculating product let result = num1 * num2 print(“Function 1: Product = “, result) } // Function 2 func product(num1: Int, num2: Int, num3: Int){ // Calculating product let result = num1 * num2 * num3 print(“Function 2: Product = “, result) } // Function 3 func product(num1: Int, num2: Int, num3: Int, num4: Int){ // Calculating product let result = num1 * num2 * num3 * num4 print(“Function 3: Product = “, result) } // Calling function 1 product(num1: 23, num2: 34) // Calling function 2 product(num1: 53, num2: 34, num3: 34) // Calling function 3 product(num1: 23, num2: 34, num3: 55, num4: 21) Output It will produce the following output − Function 1: Product = 782 Function 2: Product = 61268 Function 3: Product = 903210 Overloading with Different Parameter Types A function can be overloaded with different parameter types which means multiple functions contain the same name and number of parameters but the parameter types are different. In this type of function overloading, the function is invoked according to the type of parameters provided by the user during the function call. Example Swift program to add two strings using nested function. import Foundation // Function 1 func Addition(num1: Int, num2: Int){ // Adding two values let result = num1 + num2 print(“Function 1: Result = “, result) } // Function 2 func Addition(num1: String, num2: String){ // Adding two values let result = num1 + num2 print(“Function 2: Result = “, result) } // Calling function 1 Addition(num1: 23, num2: 34) // Calling function 2 Addition(num1: “Hello!”, num2: “Tutorialspoint”) Output It will produce the following output − Function 1: Result = 57 Function 2: Result = Hello!Tutorialspoint Overloading with Argument Label We can overload functions according to their argument labels. In such type of overloading, the function names are the same but the argument label is different. So that at the time of execution compiler can easily identify which function should it invoke. Example Swift program to overload function according to their argument labels. import Foundation // Function 1 func Area(length: Int, width: Int){ let result = length * width print(“Function 1: Result=”, result) } // Function 2 func Area(l: Int, w: Int){ let result = l * w print(“Function 2: Result=”, result) } // Calling function 1 Area(length: 23, width: 3) // Calling function 2 Area(l:13, w: 3) Output It will produce the following output − Function 1: Result= 69 Function 2: Result= 39 Advantages of Function Overloading in Swift The following are the advantages of function overloading − It improves the code readability. Reduce multiple function names by giving the same name to all the functions. It enhances type safety and reduces runtime errors. Print Page Previous Next Advertisements ”;

Swift – Nested Functions

Swift – Nested Functions ”; Previous Next A Function is a block of statements that is called to perform a specific task. When a function is defined inside another function, such type of function is known as a nested function. The scope of the nested function is limited to the function in which they are defined means they are only accessible from within the outer function. If we try to access them outside the outer function, then we will get the error. In Swift, a single function can contain multiple nested functions and they must be defined before they are called. The nested function increases the readability and organizes complex tasks by breaking them into smaller and reusable components. Nested functions encapsulate the logic inside the limited scope and can prevent external access. They can only access variables from their outer function. Syntax of Nested Functions Following is the syntax of the Nested Function − func outerFunction(){ func nestedFunction(){ // code } func nestedFunction2(){ //code } nestedFunction1() nestedFunction2() } Nested Function Without Parameter in Swift In Swift, we can define a nested function without any parameters. Such a type of function does not take any parameter while calling them and may or may not return any value. Syntax Following is the syntax of the nested function without a parameter list − func nestedFunction(){ // Code } Example Swift program to display the World Cup winner”s name using nested function. import Foundation // Outer function func worldCupTrophy(){ // Nested function without parameter list func winnerName() { print(“Winner of World Cup is INDIA”) } // Calling nested function winnerName() } // Calling the outer function to display the result worldCupTrophy() Output It will produce the following output − Winner of World Cup is INDIA Nested Function with Parameter in Swift A nested function can contain a parameter list without any return type. Such types of nested functions can only access variables and parameters of the outer function. A nested function can contain multiple parameters and they are separated by their argument labels. Syntax Following is the syntax of Nested Function with Parameters − func nestedFunction(name1: Int, name2: Int){ // code } Example Swift program to add two strings using nested function. import Foundation // Outer function func concatenateStrings(str1: String, str2: String){ // Nested function with parameter list func displayResult(finalStr: String) { print(“Concatenated String: (finalStr)”) } let result = str1 + str2 // Calling nested function displayResult(finalStr: result) } // Input strings var string1 = “Welcome “ var string2 = “TutorialsPoint” // Calling the outer function to display the result concatenateStrings(str1: string1, str2: string2) Output It will produce the following output − Concatenated String: Welcome TutorialsPoint Nested Function without Return Type in Swift A nested function without any return type does not return any value. It may or may not contain parameters. Syntax Following is the syntax of Nested Function without return type − func nestedFunction(name: Int){ // code return } Example Swift program to calculate the area of a rectangle using nested function. import Foundation // Outer function func Rectangle(length: Int, width: Int){ // Nested function without return type func displayArea(finalArea: Int) { print(“Area of Rectangle: (finalArea)”) } let result = length * width // Calling nested function displayArea(finalArea: result) } // Input strings var l = 10 var w = 12 // Calling the outer function to display the result Rectangle(length: l, width: w) Output It will produce the following output − Area of Rectangle: 120 Nested Function with Return Type in Swift A nested function can contain a parameter list without any return type. A nested function with a return type always returns something. Syntax Following is the syntax of Nested Function with Return Type − func nestedFunction(name1: Int, name2: Int) -> ReturnType{ // code return } Example Swift program to calculate the sum of two figures(rectangle and square) using nested function. import Foundation // Outer function without return type func Areas(length: Int, width: Int){ // Nested function with return type func sumOfAreas(area1: Int, area2: Int)-> Int { let Sum = area1 + area2 return Sum } let areaOfRectangle = length * width let areaOfSquare = length * length // Calling nested function print(“Total Area: (sumOfAreas(area1: areaOfRectangle, area2: areaOfSquare))”) } // Calling the outer function to display the result Areas(length: 23, width: 25) Output It will produce the following output − Total Area: 1104 Print Page Previous Next Advertisements ”;

Swift – Functions

Swift – Functions ”; Previous Next A function is a set of statements organized together to perform a specific task. A Swift function can be as simple as a simple C function to as complex as an Objective C language function. It allows us to pass local and global parameter values inside the function calls. Also, we can define a function inside another function to encapsulate its functionality inside another function. Function plays an important role in structuring code, modularity and increasing code readability. They also provide various features such as parameter labels, default parameter values, variadic parameters, and multiple return types. Function Definition in Swift In Swift, a function is defined by the “func” keyword. When a function is newly defined, it may take one or several values as input ”parameters” to the function and it will process the functions in the main body and pass back the values to the functions as output ”return types”. Every function has a function name, which describes the task that the function performs. To use a function, you “call” that function with its name and pass input values (known as arguments) that match the types of the function”s parameters. Function parameters are also called as ”tuples”. A function”s arguments must always be provided in the same order as the function”s parameter list and the return values are followed by ->. Syntax Following is the syntax for creating a function − func funcname(Parameters) -> returntype { Statement1 Statement2 — Statement N return parameters } Example Swift program to demonstrate how to create a function. // Function with return type func student(name: String) -> String { return name } print(student(name: “First Program”)) print(student(name:”About Functions”)) Output It will produce the following output − First Program About Functions Calling a Function in Swift Calling a function means executing the set of statements present inside the function. We can call a function through its name and at the time of calling it is necessary to provide all the arguments (if available). Let us suppose we defined a function called ”display” to Consider for example to display the numbers a function with function name ”display” is initialized first with argument ”no1” which holds integer data type. Then the argument ”no1” is assigned to argument ”a” which hereafter will point to the same data type integer. Now the argument ”a” is returned to the function. Here display() function will hold the integer value and return the integer values every time the function is invoked. Syntax Following is the syntax for calling a function − funcName(parameters) Example Swift program to demonstrate how to call a function. // Creating function func display(no1: Int) -> Int { let a = no1 return a } // Calling function print(display(no1: 100)) print(display(no1: 200)) Output It will produce the following output − 100 200 Type of Function Parameters in Swift Parameters are the variables that are specified in the function declaration to get input when the function is called. Or they allow us to pass values to the function at the time of calling and can perform operations on those values. They are always specified inside the function along with the label, type and value(if available). Swift function supports the following types of parameters − Regular Parameters Varadic Parameters In-Out parameters Let us discuss all types of parameters in detail. Regular Parameters Regular parameters are the most commonly used parameters in the function. They allow us to perform basic operations according to the specified value. A function can have a single or multiple regular parameters. Each regular parameter has its argument label, and explicit type and they are separated by comma. We can also specify the default value in the regular parameter, which means if we omit that parameter while calling that function, then the default value present in that parameter will used. Syntax Following is the syntax for regular parameters − func funcname(name1: Type, name2:Type = defualtValue) -> returntype { Statement return value } Example Swift program to demonstrate how to create a function with regular parameters. // Creating function with regular parameters and default value func Sum(num1: Int, num2: Int = 2) -> Int { var result = 0 result = num1 + num2 return result } // Calling function print(“Sum 1:”, Sum(num1: 10)) print(“Sum 2:”, Sum(num1: 20, num2: 12)) Output It will produce the following output − Sum 1: 12 Sum 2: 32 Variadic Parameters Swift provide a special type of parameter named a varadic parameter. The variadic parameter allows us to accept multiple input values of the same type in the function. This parameter is useful when we want to pass an arbitrary number of values of the same type inside the function without specifying the exact count of the values. A single function can contain multiple variadic parameters and after the first variadic parameter, the next variadic parameters must contain argument labels to distinguish them. The values passed inside the variadic parameters are available as an array in the function. A variadic parameter is not marked as inout. Syntax Following is the syntax for variadic parameters − func funcname(_name1: Type…, name2:Type…, name3: Type…) -> returntype { Statement return value } Example Swift program to demonstrate how to create a function with varadic parameters. // Creating function with variadic parameter func Product(_ num: Int…) -> Int { var result = 1 for x in num{ result *= x } return result } // Calling function and passing multiple values of the same type print(“Product:”, Product(10, 20, 30)) Output

Swift – fall through statement

Swift – Fallthrough Statement ”; Previous Next A switch statement in Swift completes its execution as soon as the first matching case is completed instead of falling through the bottom of subsequent cases as it happens in C and C++ programming languages. The generic syntax of a switch statement in C and C++ is as follows − switch(expression){ case constant-expression : statement(s); break; /* optional */ case constant-expression : statement(s); break; /* optional */ /* you can have any number of case statements */ default : /* Optional */ statement(s); } Here we need to use a break statement to come out of a case statement, otherwise, the execution control will fall through the subsequent case statements available below the matching case statement. So in Swift, we can achieve the same functionality using a fallthrough statement. This statement allows controls to transfer to the next case statement regardless of whether the current case’s condition is matched. Due to this, it is less preferred by the developers because it makes code less readable or can lead to unexpected behaviour. Syntax Following is the syntax of the fallthrough statement − switch expression { case expression1 : statement(s) fallthrough /* optional */ case expression2, expression3 : statement(s) fallthrough /* optional */ default : /* Optional */ statement(s); } If we do not use the fallthrough statement, then the program will come out of the switch statement after executing the matching case statement. We will take the following two examples to make its functionality clear. Example Swift program to demonstrate the use of switch statement without fallthrough. import Foundation var index = 10 switch index { case 100 : print( “Value of index is 100”) case 10,15 : print( “Value of index is either 10 or 15”) case 5 : print( “Value of index is 5”) default : print( “default case”) } Output It will produce the following output − Value of index is either 10 or 15 Example Swift program to demonstrate the use of switch statement with fallthrough. import Foundation var index = 10 switch index { case 100 : print( “Value of index is 100”) fallthrough case 10,15 : print( “Value of index is either 10 or 15”) fallthrough case 5 : print( “Value of index is 5”) default : print( “default case”) } Output It will produce the following output − Value of index is either 10 or 15 Value of index is 5 Print Page Previous Next Advertisements ”;

Swift – Sets

Swift – Sets ”; Previous Next Swift sets are used to store distinct values of the same types but they don’t have definite ordering as arrays have. It runs a strict type checking which means you are not allowed to enter a wrong type in an array, even by mistake. If you assign a created set to a variable, then it is always mutable, which means you can change it by adding, removing, or changing its elements. But if you assign a set to a constant, then that set is immutable, which means you cannot able to add new elements to that set. If you try to do so, the compiler will throw an error. The Set uses a hash table to store elements. All the basic swift values are of hashable type by default and may be used as set values. Creating Sets in Swift To create an empty set of a certain type we can use the Set() initializer. It explicitly accepts the data type. A set can store the value of any data type like float, integer, string, character and double. var someSet = Set<DataType>() We can also create an empty set using the array literal. It is the shorthand representation of a set. var someSet : Set<DataType> = [value] Or var someSet : Set = [value] Initializing Sets in Swift We can initialize the set using the following methods − Using insert() method It is a pre-defined function to add new elements to the set. It adds one element at a time. Syntax Following is the syntax for insert() function − set.insert(x) Example import Foundation // Initialize an empty set of String var mySet = Set<String>() // Inserting elements into the set using insert() function mySet.insert(“Swift”) mySet.insert(“C++”) mySet.insert(“C”) mySet.insert(“Java”) // Displaying set print(mySet) Output It will produce the following output − [“Java”, “C”, “Swift”, “C++”] Using array literal We can also initialize a set using array literal. It is the easiest way to initialize a set. Also using this method, we can initialize a set with multiple values. Syntax Following is the syntax for array literal − var someSet : Set = [value1, value2, value3] Example import Foundation // Initialize a set of integers using an array literal var mySet1 : Set = [3, 55, 6, 22] var mySet2 : Set<String> = [“Swift”, “Java”, “C”, “C++”] // Displaying set print(“Set 1:”, mySet1) print(“Set 2:”, mySet2) Output It will produce the following output − Set 1: [3, 6, 55, 22] Set 2: [“C++”, “Swift”, “C”, “Java”] Iterating over a Set in Swift Iterating over a set allows the developer to access and process individual elements of the given set. In Swift, we can iterate over a set using the following methods − Using for-in loop We can use a for-in loop to iterate over elements of the given set. It is the easiest and cleanest way to access and process each element of the given set sequentially. Example import Foundation // Initialize a set of integers using an array literal var mySet1 : Set = [3, 55, 6, 22] print(“Elements of Set:”) // Iterating through each element of the set // Using for-in for x in mySet1{ print(x) } Output It will produce the following output − Elements of Set: 22 6 3 55 Using the enumerated() Function with for-in loop If we want to fetch all the elements along with their corresponding index value then we can use the enumerated() function along with a for-in loop. Example import Foundation // Initialize a set of integer type var mySet1 : Set = [3, 55, 6, 22] print(“Elements of Set:”) // Iterating through each element of the set // Using for-in loop along with enumerated() function for (index, element) in mySet1.enumerated(){ print(“(element) is at index (index)”) } Output It will produce the following output − Elements of Set: 22 is at index 0 55 is at index 1 6 is at index 2 3 is at index 3 Using forEach() Function Swift provides a pre-defined function named forEach() to iterate over the given set. It is useful to perform operations on the individual elements of the given set without iterating manually. Example import Foundation // Initialize a set of integer type var mySet1 : Set = [3, 55, 6, 22] print(“Elements of Set:”) // Iterating over the set using forEach() function mySet1.forEach { num in print(num) } Output It will produce the following output − Elements of Set: 3 55 6 22 Set Operations in Swift Set operations are used for combining, comparing and manipulating sets. A set supports five types of operations − Union Intersection Subtraction Difference Subset Now let us discuss them in detail. Union Union is used to combine the elements of two sets into a single set without duplicate elements. For example, we have two sets set1 = [2, 4, 5] and set2 = [7, 8, 9] so the union of both sets is [2, 4, 5, 8, 9]. To perform union operation on set Swift provides a pre-defined function named union(). This method returns the union of two sets. Syntax Following is the syntax for union − Set1.union(set2) Example import Foundation // Initialize a set of integer type var mySet1 : Set = [3, 55, 6, 22] var mySet2 : Set = [4, 6, 21, 1] // Union of mySet1 and mySet2 var

Swift – break statement

Swift – Break Statement ”; Previous Next Swift Break Statement The break statement in Swift is designed to terminate the control flow statements prematurely. Or we can say that it is used to terminate the loop at a certain condition before reaching its final conclusion. We can use break statements with – Loop Statements Switch Statements Syntax Following is the syntax of the break statement − break Flow Diagram The following flow diagram will show how the break statement works − Swift break Statement with Loops The break statement is commonly used with loops. In a loop, when the break condition is true, the loop immediately terminates its iterations and the controls will return to the statement present just after the loop. We can use break statement inside the for-in loop, while loop and in nested loops. If we are using nested loops (i.e., one loop inside another loop), then the break statement will stop the execution of the innermost loop and start executing the next line of the code after the block. Example Swift program to demonstrate the use of break statement in a for-in loop. import Foundation print(“Numbers:”) for x in 1…5 { if x == 3 { // When x is equal to 3 the loop will terminate break } print(x) } Output It will produce the following output − Numbers: 1 2 Example Swift program to demonstrate the use of break statement in a nested loop. import Foundation // Outer loop for x in 1…6 { // Inner loop for y in 1…5 { if y == 4 { // When y = 4 terminate the inner loops break } print(“((x), (y))”) } } Output It will produce the following output − (1, 1) (1, 2) (1, 3) (2, 1) (2, 2) (2, 3) (3, 1) (3, 2) (3, 3) (4, 1) (4, 2) (4, 3) (5, 1) (5, 2) (5, 3) (6, 1) (6, 2) (6, 3) Example Swift program to demonstrate the use of break statement in a while loop. import Foundation var x = 2 while true { print(“Current value of x: (x)”) if x == 8 { print(“Loop ends because x is equal to 8.”) break } x += 1 } Output It will produce the following output − Current value of x: 2 Current value of x: 3 Current value of x: 4 Current value of x: 5 Current value of x: 6 Current value of x: 7 Current value of x: 8 Loop ends because x is equal to 8. Swift break Statement with Switch Statement We can also use a break statement in the switch statement to terminate the switch block after the match of a certain case and control moves to the next statement present after the switch block. All the cases present in the switch must explicitly be terminated using a break statement. By default, Swift does not fall through to the next case, however, if you want then you can use the fall-through statement. Example Swift program to demonstrate the use of a break statement in a switch statement. import Foundation let color = “Blue” switch color { case “Blue”, “Black”, “Brown”: print(“Dark colors”) // Using break statement to break the switch statement break case “baby pink”, “Blush”, “Peach”: print(“Pastel Colors”) default: print(“Invalid Color”) } Output It will produce the following output − Dark colors Print Page Previous Next Advertisements ”;

Swift – continue statement

Swift – Continue Statement ”; Previous Next The continue statement is designed to be used inside the loop to skip the code inside the loop block and process the next iteration. With the help of the continue statement, we can bypass the remaining code present inside the loop for a certain iteration according to the given condition. For a for loop, the continue statement causes the conditional test and increments the portions of the loop to execute. For while and do…while loops, the continue statement causes the program control to pass to the conditional tests. Syntax Following is the syntax of the continue statement − continue Flow Diagram The following flow diagram will show how the continue statement works − Example Swift program to demonstrate the use of continue statement. import Foundation let nums = [30, 2, 14, 7, 19, 11, 13, 10] // Loop to print even numbers for n in nums { if n % 2 != 0 { // Skip the code for odd numbers continue } // It will execute only for even numbers print(“Even Number: (n)”) } Output It will produce the following output − Even Number: 30 Even Number: 2 Even Number: 14 Even Number: 10 Example Swift program to skip -4 from the given array using continue statement. import Foundation let arr = [11, 12, 23, -4, 88, 92, 34, 2] for x in arr { if x == -4 { // When x = -4, skip the rest of the loop continue } print(“Value: (x)”) } Output It will produce the following output − Value: 11 Value: 12 Value: 23 Value: 88 Value: 92 Value: 34 Value: 2 Example Swift program to skip city names whose length is more than 5 characters using continue statement. import Foundation let city = [“Delhi”, “Mumbai”, “Jaipur”, “Pune”, “Goa”] for x in city { if x.count > 5 { // Skip those cities whose word count is more than 5 characters continue } print(“City names: (x)”) } Output City names: Delhi City names: Pune City names: Goa Print Page Previous Next Advertisements ”;

Swift – While loop

Swift – While Loop ”; Previous Next A while loop statement in Swift programming language repeatedly executes a designated statement as long as a given condition remains true. The condition is very crucial in the while loop it prevents the loop from becoming an infinite loop. So always check the condition in the while loop. The key point of a while loop is that the loop might not ever run. When the condition is tested and the result is false, the loop body will be skipped and the first statement after the while loop will be executed. Syntax The syntax of a while loop − while condition { statement(s) } Here statement(s) may be a single statement or a block of statements. The condition may be any expression. The loop iterates while the condition is true. When the condition becomes false, the program control passes to the line immediately following the loop. Flow Diagram The following flow diagram will show how the while loop works − Example The following Swift program uses the comparison operator < to compare the value of the variable index against 20. While the value of the index is less than 20, the while loop continues executing a block of code next to it and as soon as the value of the index becomes equal to 20, it comes out. import Foundation var index = 10 // Here the loop continues executing until the index is less than 20 while index < 20 { print( “Value of index is (index)”) index = index + 1 } Output It will produce the following output − When executed, the above code produces the following result − Value of index is 10 Value of index is 11 Value of index is 12 Value of index is 13 Value of index is 14 Value of index is 15 Value of index is 16 Value of index is 17 Value of index is 18 Value of index is 19 Example Swift program to find the sum using a while loop. import Foundation var sum = 0 var num = 1 // Here the loop continues executing until num is less than equal to 9 while num <= 9 { sum += num num += 1 } print(“Sum of numbers from 1 to 9 is: (sum)”) Output It will produce the following output − When executed, the above code produces the following result − Sum of numbers from 1 to 9 is: 45 Print Page Previous Next Advertisements ”;

Swift – Bitwise Operators

Swift – Bitwise Operators ”; Previous Next Bitwise Operators in Swift Bitwise operators are commonly used when we want to perform operations on the bits of the specified number. These operators are used in low-level programming, to do bit-level calculations or in communication networks to send data in bits. We can apply bitwise operators on integer types. These operators do not cause overflow because the result of bitwise operators is always within the range of the given numeric type. Swift supports the following bitwise operators − Operator Name Example ~ Bitwise NOT Operator ~(11011) = (00100) & Bitwise AND Operator (110011) & (101101) = 100001 | Bitwsie OR Operator (100011) | (10111) = 101111 ^ Bitwise XOR operator (100011) ^ (10111) = 00100 << Bitwise Left Shift Operator (100011) << 2 = 10001100 >> Bitwise Right Shift Operator (100011) >> 2 = 1000. Bitwise NOT Operator in Swift A bitwise NOT operator(~) is used to invert all the given bits(which converts 0’s into 1’s or 1’s into 0’s). Or we can say that it returns the one”s complement of the given bits. For example, we have 1100011 bits so after using the bitwise NOT operator we will get 0011100 bits as an output. It is a prefix operator and is used just before the variable it will operate on. Syntax Following is the syntax of the bitwise NOT operator − ~VariableName Example Swift program to calculate one’s complement using bitwise NOT operator. import Foundation var num : UInt8 = 0b00011111 // Finding one”s complement using bitwise NOT operator var result = ~(num) print(“Original bits:”, String(num, radix: 2)) print(“One”s complement:”, String(result, radix: 2)) Output Original bits: 11111 One”s complement: 11100000 Bitwise AND Operator in Swift A bitwise AND operator “&” is used to perform the AND operation on every bit of the given two operands. Or we can say that it is used to combine the bits of the given two numbers and return a new number whose bits are set to 1 only if both the input bits are 1. For example, A = 110011 and B = 101101, so after performing bitwise AND we get 100001. The truth table is − P Q P & Q 0 0 0 1 0 0 0 1 0 1 1 1 Syntax Following is the syntax of the bitwise AND operator − Operand1 & Operand2 Example Swift program to perform bitwise AND operation. import Foundation var num1 : UInt8 = 0b1000101 var num2 : UInt8 = 0b1100011 // Performing bitwise AND operation var result = num1 & num2 print(“Result:”, String(result, radix: 2)) Output Result: 1000001 Bitwise OR Operator in Swift A bitwise OR operator “|” is used to perform the OR operation on every bit of the given two operands. Or we can say that it is used to compare the bits of the given two numbers and return a new number whose bits are set to 1 if any of the input bits are 1. For example, A = 100011 and B = 10111, so after performing bitwise OR we get 101111. The truth table is − P Q P | Q 0 0 0 1 0 1 0 1 1 1 1 1 Syntax Following is the syntax of the bitwise OR operator − Operand1 | Operand2 Example Swift program to perform bitwise OR operation. import Foundation var num1 : UInt8 = 0b1010001 var num2 : UInt8 = 0b1100011 // Performing bitwise OR operation var result = num1 | num2 print(“Result:”, String(result, radix: 2)) Output Result: 1110011 Bitwise XOR Operator in Swift A bitwise XOR operator “^” is used to perform the XOR operation on every bit of the given two operands. Or we can say that it is used to compare the bits of the given two numbers and return a new number whose bits are set to 1 if one bit in input is 0 and another bit is 1 or vice versa For example, A = 100011 and B = 10111, so after performing bitwise XOR we get 00100. The truth table is − P Q P ^ Q 0 0 0 1 0 1 0 1 1 1 1 0 Syntax Following is the syntax of the bitwise XOR operator − Operand1 ^ Operand2 Example Swift program to perform bitwise XOR operation. import Foundation var num1 : UInt8 = 0b1011001 var num2 : UInt8 = 0b1100011 // Performing bitwise XOR operation var result = num1 ^ num2 print(“Result:”, String(result, radix: 2)) Output Result: 111010 Bitwise Left Shift Operator in Swift A bitwise left shift operator “<<” is used to shift all the bits of the given number on the left side by a given number of places. For example, A = 100011 so after shifting the bits by 2 places we get 10001100.