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 ”;

Swift – repeat…while loop

Swift – repeat…while Loop ”; Previous Next Unlike for and while loops, which test the loop condition at the top of the loop, the repeat…while loop checks its condition at the bottom of the loop. A repeat…while loop is similar to a while loop, except that a repeat…while loop is guaranteed to execute at least once before checking the loop condition. Syntax The syntax of a repeat…while loop − repeat{ statement(s); } while( condition ); It should be noted that the conditional expression appears at the end of the loop, so the statement(s) in the loop execute once before the condition is tested. If the condition is true, the control flow jumps back up to repeat, and the statement(s) in the loop execute again. This process repeats until the given condition becomes false. Flow Diagram The following flow diagram will show how the repeat-while loop works − Example Swift program to demonstrate the use of repeat while loop. import Foundation var index = 10 repeat { print( “Value of index is (index)”) index = index + 1 } while index < 20 Output It will produce the following output − 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 of numbers from 1 to 10 using repeat while loop. import Foundation var sum = 0 var num = 1 repeat { sum += num num += 1 } while num <= 10 print(“Sum of numbers from 1 to 10 is: (sum)”) Output It will produce the following output − Sum of numbers from 1 to 10 is: 55 Print Page Previous Next Advertisements ”;

Swift – if-else Statement

Swift – If… Else Statement ”; Previous Next An if-else statement allows you to execute different blocks of code according to the given expression. If the given condition is true, then the code present inside the if statement will execute and if the given condition is false, then the code present inside the else statement will execute. Or we can say that an if-else statement is the modified version of an if statement where an if statement can be followed by an optional else statement, which executes when the Boolean expression is false. For example, Ram is going to market and his mother tells him that if you find apples on sale then buy them otherwise buy grapes. So here the if condition is “Apple on sale” and the else condition is “buy Grapes”. Hence Ram will buy Apple only when the if condition is true. Otherwise, he will buy grapes. Syntax Following is the syntax of the if…else statement − if boolean_expression{ /* statement(s) will execute if the boolean expression is true */ } else{ /* statement(s) will execute if the boolean expression is false */ } If the Boolean expression evaluates to true, then the if block of code will be executed, otherwise else block of code will be executed. Flow Diagram The following flow diagram will show how if…else statement works. Example Swift program to demonstrate the use of if… else statement. import Foundation var varA:Int = 100; /* Check the boolean condition using if statement */ if varA < 20 { /* If the condition is true then print the following */ print(“varA is less than 20”); } else { /* If the condition is false then print the following */ print(“varA is not less than 20”); } print(“Value of variable varA is (varA)”); Output It will produce the following output − varA is not less than 20 Value of variable varA is 100 Example Swift program to check even or odd numbers using if-else statement. import Foundation let num = 41 if num % 2 == 0 { print(“Entered number is even.”) } else { print(“Entered number is odd.”) } Output It will produce the following output − Entered number is odd. Example Swift program to check the correct username using an if-else statement. import Foundation let username = “123Admin22″ let inputUsername = “123Admin22″ if username == inputUsername { print(“Login successful.”) } else { print(“Invalid username.”) } Output It will produce the following output − Login successful. Print Page Previous Next Advertisements ”;

Swift – Loops

Swift – Loops ”; Previous Next Swift Loops A loop statement allows us to execute a statement or group of statements multiple times. They execute in a sequential manner like the first statement in a function is executed first, followed by the second, and so on. A loop can run infinite times until the given condition is false. For example, we want to print a series of numbers from 1 to 10. So to print the sequence we can specify 1…10 range in the for-in loop and the loop ends when it encounters 10. Following is the general form of a loop statement in most programming languages − Loop Name Description for-in Iterates through each element of the given sequence or collection such as array, ranges, etc. and can perform operation on them if needed. while loop Repeats a statement or group of statements while a given condition is true. It tests the condition before executing the loop body. repeat…while loop Like a while statement, except that it tests the condition at the end of the loop body. Swift programming language provides the following kinds of loops to handle looping requirements. 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 Swift – Loop Control Statements Loop control statements allow the developer to change the execution of loops from its normal sequence. They are designed to transfer controls from one block of statements to another. When execution leaves a scope, all automatic objects that were created in that scope are destroyed. Swift supports the following control statements − Control Statement Description continue statement This statement tells a loop to terminate what it is doing and start again at the beginning of the next iteration through the loop. break statement Terminates the loop statement and transfers execution to the statement immediately following the loop. fallthrough statement The fall through statement simulates the behavior of Swift 4 switch to C-style switch. Example Swift program to demonstrate the use of break statement in a for-in loop. import Foundation print(“Numbers:”) for y in 1…8 { if y == 5 { // When y is equal to 5 the loop will terminate break } print(y) } print(“Hello Swift”) Output It will produce the following output − Numbers: 1 2 3 4 Hello Swift Print Page Previous Next Advertisements ”;

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 – if…else if…else Statement

Swift – if…else if…else Statement ”; Previous Next An if statement can be followed by an optional else if…else statement, which is very useful to test various conditions using a single if…else if statement. Or we can say that if… else if…else statements allow you to check multiple conditions sequentially. It creates a decision tree where each condition is evaluated in an order and the first true condition’s block of statement will execute. If no condition is true, then the else part will execute. If…else if…else statements are also known as if… else ladder. When using if, else if, and else statements, there are a few points to keep in mind. An if can have zero or one else”s and it must come after any else if”s. An if can have zero to many else if”s and they must come before the else. Once an else if succeeds, none of the remaining else if”s or else”s will be tested. Syntax Following is the syntax of the if…else if…else statement − if boolean_expression1{ /* Execute when the boolean expression 1 is true */ } else if boolean_expression2{ /*Execute when the boolean expression 2 is true*/ } else if boolean_expression3{ /*Execute when the boolean expression 3 is true*/ }else{ /* Execure when none of the above conditions is true */ } Flow Diagram The following flow diagram will show how if…else if…else statement works. Example Swift program to demonstrate the use of if… else if…else statement. import Foundation var varA:Int = 100; /* Check the boolean condition using the if statement */ if varA == 20 { /* If the condition is true then print the following */ print(“varA is equal to than 20”); } else if varA == 50 { /* If the condition is true then print the following */ print(“varA is equal to than 50”); } else { /* If the condition is false then print the following */ print(“None of the values is matching”); } print(“Value of variable varA is (varA)”); Output It will produce the following output − None of the values is matching Value of variable varA is 100 Example Swift program to check the current season using if…else ladder. import Foundation let myMonth = 5 // Checking Season using if…else ladder if myMonth >= 3 && myMonth <= 5 { print(“Current Season is Spring”) } else if myMonth >= 6 && myMonth <= 8 { print(“Current Season is Summer”) } else if myMonth >= 9 && myMonth <= 11 { print(“Current Season is Autumn”) } else { print(“Current Season is Winter”) } Output It will produce the following output − Current Season is Spring Example Swift program to calculate the grade of the student using if…else if…else statement. import Foundation let marks = 89 // Determine the grade of the student if marks >= 90 { print(“Grade A”) } else if marks >= 80 { print(“Grade B”) } else if marks >= 70 { print(“Grade C”) } else if marks >= 60 { print(“Grade D”) } else { print(“Grade F”) } Output It will produce the following output − Grade B Print Page Previous Next Advertisements ”;

Swift – Integers

Swift – Integers ”; Previous Next Integers data type is used to store whole numbers such as 23, -543, 0, 332, etc. It can store positive, negative and zero numbers. It does not store fractional numbers like 3.43, 4.423, etc. Swift divides integers into two categories − Signed Integers − Signed integers are used to store zero and positive integers. They are available in 8, 16, 23, and 64-bit forms. They are represented by Int like an 8-bit signed integer of type Int8. Unsigned Integers − Unsigned integers are used to store negative integers. They are also available in 8, 16, 23, and 64-bit forms. It is represented by Uint like a 32-bit unsigned integer of type UInt32. Int Swift provides a special integer type named Int. Using Int type we do not need to explicitly specify the size of the integer. The size of Int is the same as the size of the platform such as if we have a 32-bit platform then the size of Int is Int32 and if we have a 64-bit platform then the size of the Int is Int64. It can store values between -2, 147, 483, 648 and 2, 147, 483, 647. Syntax Following is the syntax of the Int − var value : Int Example Swift program to calculate the sum of two integers. import Foundation // Defining integer data type let num1 : Int = 232 let num2 : Int = 31 // Store the sum var sum = 0 // Calculate the sum sum = num1 + num2 print(“Sum of (num1) and (num2) = (sum)”) Output Sum of 232 and 31 = 263 UInt Using UInt we can also store unsigned integer data types without explicitly specifying their size. The size of Uint is also the same as the size of the platform such as if we have a 32-bit platform, then the size is UInt32 whereas if we have a 64-bit platform, then the size is UInt64. Syntax Following is the syntax of UInt − var num : Uint = 32 Example Swift program to add two unsigned integers. import Foundation // Defining Unsigned integer data type let num1 : UInt = 32 let num2 : UInt = 22 // Store the sum var sum : UInt // Calculate the sum sum = num1 + num2 print(“Sum of (num1) and (num2) = (sum)”) Output Sum of 32 and 22 = 54 Integer Bounds The minimum and maximum size of the integer data type are as follows − Type Size Range Int8 1 bytes -128 to 127 Int16 2 bytes -32768 to 32767 Int32 4 bytes -2147483648 to 2147483647 Int64 8 bytes -9223372036854775808 to 9223372036854775807 UInt8 1 bytes 0 to 255 UInt16 2 bytes 0 to 65535 UInt32 4 bytes 0 to 4294967295 UInt64 8 bytes 0 to 18446744073709551615 Minimum and Maximum size of Integer We can explicitly calculate the size of the integer with the help of the pre-defined properties of Swift min and max. The min property is used to calculate the minimum size of the integer and the max property is used to calculate the maximum size of the integer. Example Swift program to calculate the minimum size of the Int8 and UInt16. import Foundation // Minimum size of Int8 and UInt16 let result1 = Int8.min let result2 = UInt16.min print(“Minimum Size of Int8 is (result1)”) print(“Minimum Size of UInt16 is (result2)”) Output Minimum Size of Int8 is -128 Minimum Size of UInt16 is 0 Example Swift program to calculate the maximum size of the Int16 and UInt64. import Foundation // Maximum size of Int16 and UInt64 let result1 = Int16.max let result2 = UInt64.max print(“Maximum Size of Int16 is (result1)”) print(“Maximum Size of UInt64 is (result2)”) Output Maximum Size of Int16 is 32767 Maximum Size of UInt64 is 18446744073709551615 Print Page Previous Next Advertisements ”;

Swift – Assertions and Precondition

Swift – Assertions and Precondition ”; Previous Next Swift provides two special mechanisms: assertions and preconditions which allow the developers to enforce some special conditions in their programs for debugging and ensuring the correctness of the program. Both methods create robust and reliable Swift applications by catching and addressing unexpected situations occurring during the different stages of application development. Swift Assertions Assertion is a powerful debugging tool to check and fix errors or bugs in the development process of an application. Or we can say that its main purpose is to catch and identify errors or bugs at the runtime. It is represented in a boolean condition, if the condition is evaluated to true, then the program will continue its execution. Whereas if the condition is evaluated as false, then the execution of the program will end. Assertion is non-recoverable, which means if the assertion fails we cannot recover it or catch it. We can achieve assertion using the assert() function. The assert(_:_:file:line) function performs a runtime check during the development. Or we can say that it implements C-style assert. Syntax Following is the syntax for the assert() function − func assert(_condition: @autoclosure()->Bool, _message: @autoclosure() -> String = String(), file: StaticString = #file, line: UInt = #line) Parameters This function takes the following parameters − condition − It represents the test condition. message − It represents the message that will be displayed when the condition is set to false. By default, its value is empty. file − It represents the file name where the assertion is present and will display along with the message if the assertion is failed. It is an optional parameter. line − It represents the line number where the assertion is present and will display along with the message if the assertion is failed. It is an optional parameter. Example import Foundation func validateMarks(_ marks: Int) { // Assert that the marks is non-negative // If the given condition fails, then the program will terminated // And will display this message assert(marks >= 0, “Marks must be non-negative value”) print(“Marks are valid”) } validateMarks(345) Output Marks are valid Example If we enter marks in the negative, then the given condition in the assert will fail and our program will end. import Foundation func validateMarks(_ marks: Int) { // Assert that the marks is non-negative // If the given condition fails, then the program will terminated // And will display this message assert(marks >= 0, “Marks must be non-negative value”) print(“Marks are valid”) } validateMarks(-39) Output main/main.swift:8: Assertion failed: Marks must be non-negative value Current stack trace: 0 libswiftCore.so 0x00007f8870bbcdc0 _swift_stdlib_reportFatalErrorInFile + 112 1 libswiftCore.so 0x00007f887088691c <unavailable> + 1444124 2 libswiftCore.so 0x00007f8870886738 <unavailable> + 1443640 3 libswiftCore.so 0x00007f8870885220 _assertionFailure(_:_:file:line:flags:) + 419 6 swift-frontend 0x0000557401fc6b3d <unavailable> + 26479421 7 swift-frontend 0x00005574012fadb9 <unavailable> + 13061561 8 swift-frontend 0x00005574010cb4c6 <unavailable> + 10769606 9 swift-frontend 0x00005574010c79b6 <unavailable> + 10754486 …………………………………………………………….. ………………………………………………………….. ………………………………………………………… Swift Precondition Precondition is used to catch and handle unexpected states and assumptions at the time of execution of the code. Or we can say that precondition helps the developer to find issues in the production state of the application. It is also represented in a boolean condition, if the condition is evaluated to true, then the program will continue its execution. Whereas if the condition is evaluated as false, then the execution of the program will end. It is also non-recoverable. We can achieve precondition using the precondition() function. The precondition(_:_:file:line) function is used to enforce a condition during the execution of the program Syntax Following is the syntax for the assert() function − func precondition(_condition: @autoclosure()->Bool, _message: @autoclosure() -> String = String(), file: StaticString = #file, line: UInt = #line) Parameters This function takes the following parameters − condition − It represents the test condition. message − It represents the message that will be displayed when the condition is set to false. By default, its value is empty. file − It represents the file name where the precondition is present and will display along with the message if the precondition is failed. It is an optional parameter. line − It represents the line number where the precondition is present and will display along with the message if the precondition is failed. It is an optional parameter. Example import Foundation func modulus(_ num: Int, by deno: Int) -> Int { // Ensure that the denominator is not zero before performing the modulus precondition(deno != 0, “The value of denominator must be non-zero”) return num % deno } let output = modulus(19, by: 3) print(“Result: (output)”) Output Result: 1 Example If we enter a zero denominator, then the given condition in the precondition will fail and our program will end. import Foundation func modulus(_ num: Int, by deno: Int) -> Int { // Ensure that the denominator is not zero before performing the modulus precondition(deno != 0, “The value of denominator must be non-zero”) return num % deno } let output = modulus(19, by: 0) print(“Result: (output)”) Output main/main.swift:6: Precondition failed: The value of denominator must be non-zero Current stack trace: 0 libswiftCore.so 0x00007fbee7245dc0 _swift_stdlib_reportFatalErrorInFile + 112 1 libswiftCore.so 0x00007fbee6f0f91c <unavailable> + 1444124 2 libswiftCore.so 0x00007fbee6f0f738 <unavailable> + 1443640 3 libswiftCore.so 0x00007fbee6f0e220 _assertionFailure(_:_:file:line:flags:) + 419 6 swift-frontend 0x0000558e85a69b3d <unavailable> + 26479421 7 swift-frontend 0x0000558e84d9ddb9 <unavailable> + 13061561 8 swift-frontend 0x0000558e84b6e4c6 <unavailable> + 10769606 9 swift-frontend 0x0000558e84b6a9b6 <unavailable> + 10754486 …………………………………………………………….. ………………………………………………………….. ………………………………………………………… Print Page Previous Next Advertisements ”;

Swift – Decision Making

Swift – Decision Making ”; Previous Next What is Decision Making Structure? Decision-making structures require that the programmer specifies one or more conditions to be evaluated or tested by the program, along with a statement or statements to be executed if the condition is determined to be true, and optionally, other statements to be executed if the condition is determined to be false. Using decision-making structure programmers can able to create flexible and responsive programs, which allows the program to take different paths according to the condition. Type of Decision-Making Statement in Swift Swift provides the following types of decision-making statements. Statement Description if statement An if statement allows you to execute a block of code if the given expression is true. if…else statement The if-else statement allows you to execute a block of code when the if condition is true. Otherwise else block will execute. if…else if…else statements The if…else if…else statements are used to check multiple conditions in sequence and execute the block of statement associated to the first true condition. Nested if statement Nested if statement is used to specify statement inside another statement. Switch statement A switch statement allows a variable to be tested for equality against a list of values. Example Swift program to demonstrate the use of switch statements. 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 if-else statements. import Foundation let X = 40 let Y = 80 // Comparing two numbers if X > Y { print(“X is greater than Y.”) } else { print(“Y is greater than or equal to X.”) } Output It will produce the following output − Y is greater than or equal to X. Swift Ternary Conditional Operator The ternary conditional operator is the shorthand representation of an if-else statement. It has three parts condition, result1 and result2. If the condition is true then it will execute the result1 and return its value. Otherwise, it will execute result2 and return its value. Syntax Following is the syntax of the ternary conditional Operator − Exp1 ? Exp2 : Exp3 Where Exp1, Exp2, and Exp3 are expressions. The value of a ? expression is determined like this: Exp1 is evaluated. If it is true, then Exp2 is evaluated and becomes the value of the entire ? expression. If Exp1 is false, then Exp3 is evaluated and its value becomes the value of the expression. Example Swift program to check whether the number is odd or even using ternary conditional operator. import Foundation let num = 34 // Checking whether the given number is odd or even // Using ternary conditional operator let result = num % 2 == 0 ? “Even” : “Odd” print(“The number is (result).”) Output It will produce the following output − The number is Even. Example Swift program to check the number is positive or negative using ternary conditional operator. import Foundation let num = 34 // Checking whether the given number is positive or negative // Using ternary conditional operator let result = num >= 0 ? “Positive” : “Negative” print(“Given number is (result).”) Output It will produce the following output − Given number is Positive. Print Page Previous Next Advertisements ”;

Swift – Optionals

Swift – Optionals ”; Previous Next Swift introduced a new feature named Optional type. The optional type handles the value that may be absent or undefined. It allows variables to represent a value or nil. The Optional are similar to using nil with pointers in Objective-C, but they work for any type, not just classes. To specify the optional type we have to use question marks(?) after the name of the type. Syntax Following is the syntax for the optional variable − var perhapsInt: Int? Example Swift program to demonstrate how to create optional variable. // Declaring an optional Integer var number: Int? // Assigning a value to the optional number = 34 // Using optional binding to safely unwrap its value if let x = number { print(“Value is (x)!”) } else { print(“Value is unknown”) } Output Value is 34! Optionals with nil If we want to specify an optional variable to a valueless state or no value, then we can assign nil to that variable. Or if we do not assign any value to an optional variable, then Swift will automatically set the value of that variable to nil. In Swift, we are only allowed to assign nil to an optional variable, if we try to assign nil to a non-optional variable or constant, then we will get an error. Syntax Following is the syntax for assigning optional to nil − var perhapsStr: Int? = nil Example Swift program to demonstrate how to assign nil to an optional variable. // Optional variable var num: Int? = 42 // Setting variable to nil num = nil // Check if the optional has a value or not if num != nil { print(“Optional has a value: (num!)”) } else { print(“Optional is nil.”) } Output Optional is nil. Forced Unwrapping If you defined a variable as optional, then to get the value from this variable, you will have to unwrap it. So to unwarp the value we have to put an exclamation mark(!) at the end of the variable. It tells the compiler that you are sure that the optional contains some value. Syntax Following is the syntax for forced unwrapping − let variableName = optionalValue! Example Swift program to demonstrate how to unwrap optional value. // Declaring an optional Integer var number: Int? // Assigning a value to the optional number = 34 // Using exclamation mark (!) to forcefully unwrapping the optional let value: Int = number! // Displaying the unwrapped value print(value) Output 34 Implicitly Unwrapping Optional You can declare optional variables using an exclamation mark instead of a question mark. Such optional variables will unwrap automatically and you do not need to use any further exclamation mark at the end of the variable to get the assigned value. Example import Cocoa var myString:String! myString = “Hello, Swift 4!” if myString != nil { print(myString) }else{ print(“myString has nil value”) } Output Hello, Swift 4! Optional Binding Use optional binding to find out whether an optional contains a value, and if so, to make that value available as a temporary constant or variable. Or we can say that optional binding allows us to unwarp and work with the value present in the optional. It prevents us from unwrapping nil values and runtime crashes. We can perform optional binding using if let, guard, and while statements. We are allowed to use multiple optional binding and boolean conditions in a single if statement, separated by a comma. If any of the optional binding or boolean conditions among the given multiple optional bindings and boolean conditions are nil, then the whole if statement is considered to be false. Syntax Following is the syntax for the optional binding − if let constantName = someOptional, let variableName = someOptional { statements } Example // Declaring an optional Integer var number: Int? // Assigning a value to the optional number = 50 // Using optional binding to safely unwrap the optional if let x = number { print(“Number is (x)!”) } else { print(“Number is unknown”) } Output Number is 50! Nil-Coalescing Operator(??) In Swift, we can also handle missing values and provide a default value if the optional is nil using the nil-coalescing operator(??). It is the shorthand method of using optional binding along with default value. Syntax Following is the syntax for the nil-coalescing operator − Let output = optionalValue ?? defaultValue The nil-coalescing operator (??) operator checks if the value on the left hand-side operand is not nil. If it is not nil, then it unwraps the value. If the value is nil, then it will provide the value (or as a fallback value) present in the right hand-side operand. Example // Function to fetch employee salary func getEmpSalary() -> Int? { // Return nil when salary is not available return nil } // Using the nil-coalescing operator to provide a valid salary let salary = getEmpSalary() ?? 5000 // Displaying the result print(“Salary: (salary)”) Output Salary: 5000 Print Page Previous Next Advertisements ”;