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 ”;
Category: Computer Programming
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 – 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 ”; 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 ”;
Solidity – Quick Guide
Solidity – Quick Guide ”; Previous Next Solidity – Overview Solidity is a contract-oriented, high-level programming language for implementing smart contracts. Solidity is highly influenced by C++, Python and JavaScript and has been designed to target the Ethereum Virtual Machine (EVM). Solidity is statically typed, supports inheritance, libraries and complex user-defined types programming language. You can use Solidity to create contracts for uses such as voting, crowdfunding, blind auctions, and multi-signature wallets. What is Ethereum? Ethereum is a decentralized ie. blockchain platform that runs smart contracts i.e. applications that run exactly as programmed without any possibility of downtime, censorship, fraud or third-party interference. The Ethereum Virtual Machine (EVM) The Ethereum Virtual Machine, also known as EVM, is the runtime environment for smart contracts in Ethereum. The Ethereum Virtual Machine focuses on providing security and executing untrusted code by computers all over the world. The EVM specialised in preventing Denial-of-service attacks and ensures that programs do not have access to each other”s state, ensuring communication can be established without any potential interference. The Ethereum Virtual Machine has been designed to serve as a runtime environment for smart contracts based on Ethereum. What is Smart Contract? A smart contract is a computer protocol intended to digitally facilitate, verify, or enforce the negotiation or performance of a contract. Smart contracts allow the performance of credible transactions without third parties. These transactions are trackable and irreversible. The concept of smart contracts was first proposed by Nick Szabo in 1994. Szabo is a legal scholar and cryptographer known for laying the groundwork for digital currency. It is fine if you do not understand Smart Contract right now, we will go into more detail later. Solidity – Environment Setup This chapter explains how we can setup Solidity compiler on CentOS machine. If you do not have a Linux machine then you can use our Online Compiler for small contracts and for quickly learning Solidity. Method 1 – npm / Node.js This is the fastest way to install Solidity compiler on your CentoS Machine. We have following steps to install Solidity Compiler − Install Node.js First make sure you have node.js available on your CentOS machine. If it is not available then install it using the following commands − # First install epel-release $sudo yum install epel-release # Now install nodejs $sudo yum install nodejs # Next install npm (Nodejs Package Manager ) $sudo yum install npm # Finally verify installation $npm –version If everything has been installed then you will see an output something like this − 3.10.10 Install solc Once you have Node.js package manager installed then you can proceed to install Solidity compiler as below − $sudonpm install -g solc The above command will install solcjs program and will make it available globally through out the system. Now you can test your Solidity compiler by issuing following command − $solcjs-version If everything goes fine, then this will print something as follows − 0.5.2+commit.1df8f40c.Emscripten.clang Now you are ready to use solcjs which has fewer features than the standard Solidity compiler but it will give you a good starting point. Method 2 – Docker Image You can pull a Docker image and start using it to start with Solidity programming. Following are the simple steps. Following is the command to pull a Solidity Docker Image. $docker pull ethereum/solc:stable Once a docker image is downloaded we can verify it using the following command. $docker run ethereum/solc:stable-version This will print something as follows − $ docker run ethereum/solc:stable -version solc, the solidity compiler commandlineinterfaceVersion: 0.5.2+commit.1df8f40c.Linux.g++ Method 3: Binary Packages Installation If you are willing to install full fledged compiler on your Linux machine, then please check official website Installing the Solidity Compiler. Solidity – Basic Syntax A Solidity source files can contain an any number of contract definitions, import directives and pragma directives. Let”s start with a simple source file of Solidity. Following is an example of a Solidity file − pragma solidity >=0.4.0 <0.6.0; contract SimpleStorage { uint storedData; function set(uint x) public { storedData = x; } function get() public view returns (uint) { return storedData; } } Pragma The first line is a pragma directive which tells that the source code is written for Solidity version 0.4.0 or anything newer that does not break functionality up to, but not including, version 0.6.0. A pragma directive is always local to a source file and if you import another file, the pragma from that file will not automatically apply to the importing file. So a pragma for a file which will not compile earlier than version 0.4.0 and it will also not work on a compiler starting from version 0.5.0 will be written as follows − pragma solidity ^0.4.0; Here the second condition is added by using ^. Contract A Solidity contract is a collection of code (its functions) and data (its state) that resides at a specific address on the Ethereumblockchain. The line uintstoredData declares a state variable called storedData of type uint and the functions set and get can be used to modify or retrieve the value of the variable. Importing Files Though above example does not have an import statement but Solidity supports import statements that are very similar to those available in JavaScript. The following statement imports all global symbols from “filename”. import “filename”; The following example creates a new global symbol symbolName whose members are all the global symbols from “filename”. import * as symbolName from “filename”; To import a file x from the same directory as the current file, use import “./x” as x;. If you use import “x” as x; instead, a different file could be referenced in a global “include directory”. Reserved Keywords Following are the reserved keywords in Solidity − abstract after alias apply auto case catch copyof default define final immutable implements in inline let macro match mutable null of override partial promise reference relocatable sealed sizeof static supports switch try typedef typeof unchecked Solidity – First Application We”re using Remix IDE to
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 ”;
Swift – Operator Overloading
Swift – Operator Overloading Operator Overloading in Swift Operator overloading is a powerful technique in Swift programming. Operator overloading allows us to change the working of the existing operators like +, -, /, *, %, etc. with the customized code. It makes code more expressive and readable. To overload an operator, we have to define the behaviour of that operator using the “static func” keyword. Syntax Following is the syntax for operator overloading − static func operatorName() { // body } Example 1 Swift program to overload + operator to calculate the sum of two complex numbers. import Foundation struct ComplexNumber { var real: Double var imag: Double // Overloading + operator to add two complex numbers static func+(left: ComplexNumber, right: ComplexNumber) -> ComplexNumber { return ComplexNumber(real: left.real + right.real, imag: left.imag + right.imag) } } let complexNumber1 = ComplexNumber(real: 2.1, imag: 2.0) let complexNumber2 = ComplexNumber(real: 6.1, imag: 9.0) // Calling + operator to add two complex numbers let sumOfComplexNumbers = complexNumber1 + complexNumber2 print(sumOfComplexNumbers) Output ComplexNumber(real: 8.2, imag: 11.0) Example 2 Swift program to overload custom prefix operator. import Foundation struct Car { var price: Double // Overloading the custom prefix operator “++” to increase the price of car static prefix func ++ (carPrice: inout Car) { carPrice.price += 500000.0 } } var currentPrice = Car(price: 2500000.0) // Calling the custom ++ operator to increase the car price ++currentPrice print(“Updated car price is”, currentPrice.price) Output Updated car price is 2500000.0 Limitation of Operator Overloading in Swift The following are the limitations of operator overloading − In Swift, you can overload limited operators like arithmetic and customized operators. While overloading operators, you are not allowed to change the precedence or associativity of the operators. Swift does not support short-circuiting behaviour for overloading logical operators. Do not overuse operator overloading because it makes your code difficult to read and understand. Difference Between Operator Function and Normal Functions The following are the major differences between the operator functions and normal functions − Operator Function Normal Function They are define using “static func” keyword and a custom operator symbol. They are defined using “func” keyword and the function name. They are used to customize the behaviours of operators. They are used to complete general purpose tasks. They are called implicitly when using operator with custom types. They are called explicitly with the help of function name. They can be defined in index, prefix or postfix form. They can only defined in infix form. Print Page Previous Next Advertisements ”;