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 ”;
Category: Computer Programming
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.
Swift – switch statement
Swift – Switch Statement ”; Previous Next A switch statement is the most powerful control statement which allows us to represent multi-branch logic in a readable manner. It provides a way to evaluate a value against the multiple given case and execute the block of statements present in the first matching case. A switch statement is an alternative to an if-else statement because a switch handles multiple conditions efficiently as compared to an if-else statement. Syntax Following is the syntax of the switch statement − switch expression{ case 1: // Statement fallthrough // Optional case 2: // Statement break // Optional default: // Statement Example The following is the example of the switch statement − 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 Swift Break Statement in Switch Statement The break statement is used to terminate the switch block immediately after executing the matched case statement block and the controls transfer to the statement present just after the switch block. Break statements are used in case blocks. Syntax Following is the syntax for the break statement − switch expression{ case x: // Statement break default: // Statement } Example The following is the example for the break statement − import Foundation let day = 4 switch day { // Case with the break statements case 1: print(“Monday”) break case 2: print(“Tuesday”) break case 3: print(“Wednesday”) break case 4: print(“Thursday”) break case 5: print(“Friday”) break default: print(“Weekend”) } Output It will produce the following output − Thursday Swift Fallthrough in Switch Statement A switch statement ends its execution as soon as it encounters its first matching case, even if we use a break statement or not. Control does not fallthrough the bottom of subsequent cases like in C and C++ programming. If we want to achieve the fallthrough feature in Swift, then we have to explicitly use the fallthrough statement in each case. The fallthrough statement allows controls to pass down to the next case even if the condition for that case is not matched. Syntax Following is the syntax for the fallthrough statement − switch expression{ case x: // Statement fallthrough default: // Statement } Example The following is the example for the fallthrough statement − import Foundation let number = 2 switch number { // Case statement with fall through case 1: print(“Hello i am case 1”) fallthrough case 2: print(“Hello i am case 2”) fallthrough case 3: print(“Hello i am case 3”) default: print(“Not found”) } Output It will produce the following output − Hello i am case 2 Hello i am case 3 Swift Ranges in Switch Statement In Swift, we are allowed to use ranges in the case statements to match a value against a range of elements. It is commonly used when we want to handle cases where the value falls in the given range. Syntax Following is the syntax for ranges in case statement − switch expression{ case x…y: // Statement default: // Statement } Example The following is the example for ranges in case statement − import Foundation let temp = 27 switch temp { // Case statement with ranges case ..<0: print(“Freezing.”) case 0…20: print(“Cold.”) case 21…30: print(“Moderate.”) case 31…: print(“Hot”) default: print(“Please enter valid temperature”) } Output It will produce the following output − Moderate. Swift Tuple Matching in Switch Statement As we know a tuple is used to store multiple values together, whether they are of the same type or not. So we are allowed to use tuple as a variable expression in the switch statement and can also use tuple to test multiple values in the case statement. We can also use the wildcard pattern “_” in the tuple. Syntax Following is the syntax for tuple matching − switch (x1, x2){ case (y, x1): // Statement default: // Statement } Example The following is the example for tuple matching − import Foundation // Switch expression in tuple let number = (num1: 25, num2: 10, num3: 11) switch number { // Case expression in tuple case (25, 10, 0): print(“Numbers are (25, 10, 0)”) case (13, _, 11): print(“Numbers are (13, 11)”) case (25, 10, 11): print(“Number are (25, 10, 11)”) default: print(“Number is not found”) } Output It will produce the following output − Number are (25, 10, 11) Swift Value Binding in Switch Statement Swift provides a new property named value binding. Using this property, we are allowed to initialize a temporary variable in the case statement and this variable is accessible only in the body of the case in which it is defined. Or we can say that it binds the match value to a temporary variable or constant inside the related block. Syntax Following is the syntax for value binding − switch expression{ case (let x, let y): // Statement default: // Statement } Example The following is the example for value binding − import Foundation let num = 17 switch num { // Value binding case let y where y % 2 == 0: print(“(num) is an even number.”) case let z
Swift – nested if statements
Swift – Nested If Statements ”; Previous Next In Swift, you are allowed to nest an if statement inside another if statement. So when the condition of the outer if statement is true, then only controls can access the nested if statement. Otherwise, the controls skipped the nested if statement and executed the block of code present right after the outer if statement. You are also allowed to nest an if statement inside an if-else statement or vice-versa. You can also nest as many if statements as you want but try to avoid excessive nesting because it”s hard to maintain if you encounter an error. Syntax Following is the syntax of the nested if statement − if boolean_expression_1{ /* statement(s) will execute if the boolean expression 1 is true */ If boolean_expression_2{ /* statement(s) will execute if the boolean expression 2 is true */ } } You can nest else if…else in a similar way as you have nested if statement. Flow Diagram The following flow diagram will show how the nested if statement works. Example Swift program to demonstrate the use of nested if statements. import Foundation var varA:Int = 100; var varB:Int = 200; /* Check the boolean condition using if statement */ if varA == 100 { /* If the condition is true then print the following */ print(“First condition is satisfied”) if varB == 200 { /* If the condition is true then print the following */ print(“Second condition is also satisfied”) } } print(“Value of variable varA is (varA)”) print(“Value of variable varB is (varB)”) Output It will produce the following output − First condition is satisfied Second condition is also satisfied Value of variable varA is 100 Value of variable varB is 200 Example Swift program to find the leap year using nested if-else statements. import Foundation let myYear = 2027 // Checking leap year if myYear % 4 == 0 { if myYear % 100 == 0 { if myYear % 400 == 0 { print(“(myYear) is a leap year.”) } else { print(“(myYear) is not a leap year.”) } } else { print(“(myYear) is a leap year.”) } } else { print(“(myYear) is not a leap year.”) } Output It will produce the following output − 2027 is not a leap year. Example Swift program to check if the given number is positive or negative even or odd number. import Foundation let num = -11 // Checking if the given number is positive // or negative even or odd number if num > 0 { if num % 2 == 0 { print(“Positive even number.”) } else { print(“Positive odd number.”) } } else if num < 0 { if num % 2 == 0 { print(“Negative even number.”) } else { print(“Negative odd number.”) } } else { print(“Number is zero.”) } Output It will produce the following output − Negative odd number. Print Page Previous Next Advertisements ”;
Socket.IO – Internals
Socket.IO – Internals ”; Previous Next In this chapter, we will discuss regarding Fallbacks, Connection using Socket.IO, Events and Messages. Fallbacks Socket.IO has a lot of underlying transport mechanisms, which deal with various constraints arising due to cross browser issues, WebSocket implementations, firewalls, port blocking, etc. Though W3C has a defined specification for WebSocket API, it is still lacking in implementation. Socket.IO provides us with fallback mechanisms, which can deal with such issues. If we develop apps using the native API, we have to implement the fallbacks ourselves. Socket.IO covers a large list of fallbacks in the following order − WebSockets FlashSocket XHR long polling XHR multipart streaming XHR polling JSONP polling iframes Connection using Socket.IO The Socket.IO connection begins with the handshake. This makes the handshake a special part of the protocol. Apart from the handshake, all the other events and messages in the protocol are transferred over the socket. Socket.IO is intended for use with web applications, and therefore it is assumed that these applications will always be able to use HTTP. It is because of this reasoning that the Socket.IO handshake takes place over HTTP using a POST request on the handshake URI (passed to the connect method). Events and Messages WebSocket native API only sends messages across. Socket.IO provides an addition layer over these messages, which allows us to create events and again helps us develop apps easily by separating the different types of messages sent. The native API sends messages only in plain text. This is also taken care of by Socket.IO. It handles the serialization and deserialization of data for us. We have an official client API for the web. For other clients such as native mobile phones, other application clients also we can use Socket.IO using the following steps. Step 1 − A connection needs to be established using the same connection protocol discussed above. Step 2 − The messages need to be in the same format as specified by Socket.IO. This format enables Socket.IO to determine the type of the message and the data sent in the message and some metadata useful for operation. The message format is − [type] : [id (”+”)] : [endpoint] (: [data] The parameters in the above command are explained below − Type is a single digit integer, specifying what type message it is. ID is message ID, an incremental integer used for acknowledgements. Endpoint is the socket endpoint that the message is intended to be delivered to… Data is the associated data to be delivered to the socket. In case of messages, it is treated as plain text, for other events, it is treated as JSON. In the next chapter, we will write a chat application in Socket.IO. Print Page Previous Next Advertisements ”;