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 ”;
Category: Computer Programming
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 ”; 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 – Type Aliases
Swift – Type Aliases ”; Previous Next Swift provides a special feature named Type Aliases. Type aliases are used to define another name or aliases for the pre-defined types. It only gives a new name to the existing type and does not create a new type. For example, “Int” can also be defined as “myInt”. After defining type alias, we can use that alias anywhere in the program. A single program can contain more than one alias. A type alias is commonly used to improve code readability, code quality and abstracting complex types. We can define type aliases with the help of the type alias keyword. Syntax Following is the syntax of the type alias – typealiase newName = existingType We can define type aliases for the following data types − Primitive Data Types User Defined Data Types Complex Data Types Type Aliases for Primitive Data Types in Swift Primitive data types are the pre-defined data types provided by Swift such as Int, Float, Double, Character and String. With the help of a type alias, we can provide a new name to the in-built data types which can be used throughout the program without any error. For example, “typealias myString = String” now using myString we can create a string type variable. Syntax Following is the syntax of the type alias for primitive data types − typealias newName = PreDefinedDataType Here the PreDefinedDataType can be Int, Float, Double, String and Character. Example Swift program to create a type alias for in-built data types. import Foundation // Creating type typealias for String typealias myString = String // Creating type typealias for Float typealias myNum = Float // Creating type typealias for Int typealias Num = Int // Declaring integer type variable using Num var number : Num = 10 // Declaring string type variable using myString var newString : myString = “Tutorialspoint” // Declaring float type variable using myNum var value : myNum = 23.456 print(“Number:”, number) print(“type:”, type(of: number)) print(“nString:”, newString) print(“type:”, type(of: newString)) print(“nFloat:”, value) print(“type:”, type(of: value)) Output Number: 10 type: Int String: Tutorialspoint type: String Float: 23.456 type: Float Type Aliases for User- Defined Data Types in Swift Using type aliases, we can also provide an alternate name to the user-defined data types. For example, “typealias mySet = Set<String>” now using mySet we can create a set of string type. Syntax Following is the syntax of the type alias for user-defined data types − typealias newName = dataType Here the datatype can be Array, Set, dictionary, etc. Example Swift program to create a type alias for user-defined data types. import Foundation // Creating type typealias for Set typealias mySet = Set<Int> // Creating type typealias for Array typealias myNum = Array<Int> // Creating type typealias for Array typealias Num = Array<String> // Declaring set of integer type using mySet var newSet : mySet = [32, 3, 1, 2] // Declaring array of integer type using myNum var newArray : myNum = [32, 2, 1, 1, 3] // Declaring array of string type using Num var newArr : Num = [“Swift”, “C++”, “C#”] print(“Set:”, newSet) print(“Array:”, newArray) print(“Array:”, newArr) Output Set: [32, 3, 1, 2] Array: [32, 2, 1, 1, 3] Array: [“Swift”, “C++”, “C#”] Type Aliases for Complex Data Types in Swift Complex data are the special type of data types which contain more than one pre-defined data type. So using types aliases we can also create aliases of complex data types. For example, (String, String) -> string as “MyString”. Syntax Following is the syntax of type aliases for complex data types − typealias newName = CdataType Here the CdataType can be any complex data type like (String)->(String). Example Swift program to create a type alias for complex data types. import Foundation // Creating type typealias for function type typealias Value = (String, String) -> String func addStr(s1: String, s2: String) -> String{ return s1 + s2 } // Assigning addStr function to Value var newFunc : Value = addStr // Calling function var result = newFunc(“Hello”, “World”) print(result) Output HelloWorld Print Page Previous Next Advertisements ”;