Swift – Floating-Point Numbers

Swift – Floating-Point Numbers ”; Previous Next Floating Point Numbers are used to store numbers with their fractional components like 3.2232, 92.2, 21.2, etc. Or we can say that the Float data type is used to store 32-bit floating point numbers. It has a precision of at least 6 decimal digits. We are allowed to perform various arithmetic operations on Floating point numbers in Swift such as addition, subtraction, multiplication, etc. We can also compare two floating point numbers using equal to or not equal to operators. Syntax Following is the syntax of the Float data type − let num : Float = 2.3421 Following is the shorthand syntax of the Float data type − let num = 3.21 Example Swift program to calculate the product of two floating point numbers. import Foundation // Defining Float data type var num1 : Float = 2.342 var num2 : Float = 23.44 // Store the result var result : Float // Calculating the product of the Floating point numbers result = num1 * num2 print(“Product of (num1) * (num2) is (result)”) Output Product of 2.342 * 23.44 is 54.89648 Example Swift program to calculate the sum of all the elements present in an array of float types. import Foundation // Defining Float type array var Array: [Float] = [2.3, 3.4, 6.5, 66.4, 3.2] // Store the sum var Sum : Float = 0.0 // Calculating the sum of all the elements present in the array for num in Array { Sum += num } print(“Sum = (Sum)”) Output Sum = 81.799995 Print Page Previous Next Advertisements ”;

Solidity – View Functions

Solidity – View Functions ”; Previous Next View functions ensure that they will not modify the state. A function can be declared as view. The following statements if present in the function are considered modifying the state and compiler will throw warning in such cases. Modifying state variables. Emitting events. Creating other contracts. Using selfdestruct. Sending Ether via calls. Calling any function which is not marked view or pure. Using low-level calls. Using inline assembly containing certain opcodes. Getter method are by default view functions. See the example below using a view function. Example pragma solidity ^0.5.0; contract Test { function getResult() public view returns(uint product, uint sum){ uint a = 1; // local variable uint b = 2; product = a * b; sum = a + b; } } Run the above program using steps provided in Solidity First Application chapter. Output 0: uint256: product 2 1: uint256: sum 3 Print Page Previous Next Advertisements ”;

Swift – Strings

Swift – Strings ”; Previous Next Strings in Swift are an ordered collection of characters, such as “Hello, World!” and they are represented by the Swift data type String, which in turn represents a collection of values of characters. Or we can say that Strings are used to represent textual information. Create a String in Swift In Swift, we can create a string in two different ways, either by using a string literal or by creating an instance of a String class. Syntax Following is the syntax for string − // Using String literal var str = “Hello” var str : String = “Hello” // Using String class var str = String(“Hello”) Example Swift program to demonstrate how to create a string. import Foundation // Creating string using String literal var stringA = “Hello, Swift!” print(stringA) // Creating string by specifying String data type var stringB : String = “Hello, Swift!” print(stringB) // Creating string using String instance var stringC = String(“Hello, Swift!”) print(stringC) Output Hello, Swift! Hello, Swift! Hello, Swift! Empty String in Swift An empty string is a string that contains nothing. It is represented by double quotes with no characters. It is generally used to initialize string variables before they receive value dynamically. We can create an empty String either by using an empty string literal or creating an instance of a String class. Syntax Following is the syntax for empty string − // Using String literal var str = “” var str : String = “” // Using String class var str = String(“”) Example Swift program to demonstrate how to create an empty string. import Foundation // Creating empty string using String literal var stringA = “” // Creating empty string by specifying String data type var stringB : String = “” // Creating string using String instance var stringC = String(“”) // Appending values to the empty strings stringA = “Hello” stringB = “Swift” stringC = “Blue” print(stringA) print(stringB) print(stringC) Output Hello Swift Blue Using the isEmpty property We can also check whether a string is empty or not using the Boolean property isEmpty. If the specified string is empty, then it will return true. Or if the specified string contains some letters, then it will return false. Example Swift program to check whether the given string is an empty string or not. import Foundation // Creating empty string using String literal var stringA = “” if stringA.isEmpty { print( “stringA is empty” ) } else { print( “stringA is not empty” ) } // Creating string let stringB = “Tutorialspoint” if stringB.isEmpty { print( “stringB is empty” ) } else { print( “stringB is not empty” ) } Output stringA is empty stringB is not empty String Mutability in Swift We can categorize a string into two types according to its ability to change after deceleration. Mutable strings: Mutable strings are those strings whose values can change dynamically after creation. Mutable strings are created using the var keyword. Immutable Strings: Immutable strings are those strings whose values cannot change after creation, if we try to change its value we will get an error. If we want to modify the immutable string, then we have to create a new string with the modified changes. Immutable strings are created using the let keyword. Example of Mutable Strings Swift program to create a mutable string. import Foundation // stringA can be modified var stringA = “Hello, Swift 4!” stringA += “–Readers–“ print(stringA) Output Hello, Swift 4!–Readers– Example of immutable Strings Swift program to create an immutable string. import Foundation // stringB can not be modified let stringB = String(“Hello, Swift 4!”) stringB += “–Readers–“ print(stringB) Output main.swift:5:9: error: left side of mutating operator isn”t mutable: ”stringB” is a ”let” constant stringB += “–Readers–“ ~~~~~~~ ^ main.swift:4:1: note: change ”let” to ”var” to make it mutable let stringB = String(“Hello, Swift 4!”) ^~~ var String Interpolation in Swift String interpolation is a powerful and convenient technique to create a new string dynamically by including the values of constants, variables, literals, and expressions inside a string literal. Each item (variable or constant or expression) that we want to insert into the string literal must be wrapped in a pair of parentheses, prefixed by a backslash (). Syntax Following is the syntax for string interpolation − let city = “Delhi” var str = “I love (city)” Example Swift program for string interpolation. import Foundation var varA = 20 let constA = 100 var varC : Float = 20.0 // String interpolation var stringA = “(varA) times (constA) is equal to (varC * 100)” print(stringA) Output 20 times 100 is equal to 2000.0 String Concatenation in Swift String concatenation is a way of combining two or more strings into a single string. We can use the + operator to concatenate two strings or a string and a character, or two characters. Syntax Following is the syntax for string concatenation − var str = str1 + str2 Example Swift program for string concatenation. import Foundation let strA = “Hello,” let strB = “Learn” let strC = “Swift!” // Concatenating three strings var concatStr = strA + strB + strC print(concatStr) Output Hello,LearnSwift! String Length in Swift Swift strings do not have a length property, but we can use the count property to count the number of characters in

Swift – Variables

Swift – Variables ”; Previous Next What are Variables in Swift? A variable provides us with named storage that our programs can manipulate. Each variable in Swift has a specific type, which determines the size and layout of the variable”s memory. A variable can store the range of values within that memory or the set of operations that can be applied to the variable. Variables are statically types means once they are declared with a certain type, then their type cannot be changed, only their value can be changed. Declaring Swift Variables A variable declaration tells the compiler where and how much to create the storage for the variable. They are always declared before their use and they are declared using the var keyword. Syntax Following is the syntax of the variable − var variableName = value Example Swift program to demonstrate how to declare variables. import Foundation // Declaring variable let number = 42 print(“Variable:”, number) Output Variable: 42 We can also declare multiple variables in a single line. Where each variable has its values and is separated by commas. Syntax Following is the syntax of multiple variables − var variableA = value, variableB = value, varaibleC = value Example Swift program to demonstrate how to declare multiple variables in a single line. import Foundation // Declaring multiple variables var variableA = 42, variableB = “TutorialsPoint”, variableC = 3.3 print(“Variable 1:”, variableA) print(“Variable 2:”, variableB) print(“Variable 3:”, variableC) Output Variable 1: 42 Variable 2: TutorialsPoint Variable 3: 3.3 Type Annotations in Swift Type annotation is used to define what type of value should be stored in the variable at the time of declaration. While declaring a variable we can specify type annotation by placing a colon after the variable name followed by the type. Type annotation is rarely used if we provide an initial value at the time of declaring a variable because Swift will automatically infer the type of the variable according to the assigned value. Syntax Following is the syntax of type annotations − var variableName : Type = Value Example Swift program to demonstrate how to specify type annotation. import Foundation // Declaring variable with type annotation var myValue : String = “Swift Tutorial” print(“Variable:”, myValue) Output Variable: Swift Tutorial We can also define multiple variables of the same type in a single line. Where each variable name is separated by a comma. Syntax Following is the syntax of multiple variables − let variableA, variableB, varaibleC : Type Example Swift program to demonstrate how to specify multiple variables in single-type annotation. import Foundation // Declaring multiple variables in single-type annotation var myValue1, myValue2, myValue3 : Int // Assigning values myValue1 = 23 myValue2 = 22 myValue3 = 11 print(“Variable Value 1:”, myValue1) print(“Variable Value 2:”, myValue2) print(“Variable Value 3:”, myValue3) Output Variable Value 1: 23 Variable Value 2: 22 Variable Value 3: 11 Naming Variable in Swift Naming a variable is a very important part at the time of declaration. They should have a unique name. You are not allowed to store two variables with the same name if you try to do you will get an error. Swift provides the following rules for naming a variable − Variable names can contain any character including unicode characters. For example, var 你好 = “你好世界”. A variable name should not contain whitespace characters, mathematical symbols, arrows, private-se Unicode scalar values, or line and box drawing characters. The name of a variable can be composed of letters, digits, and the underscore character. It must begin with either a letter or an underscore. For example, var myValue = 34. Upper and lowercase letters are distinct because Swift is case-sensitive. For example, var value and var Value are two different variables. Variable names should not begin with a number. You are not allowed to re-declare a variable with the same name. Or cannot change into another type. You are not allowed to change a variable into a constant or vice versa. If you want to declare a variable name the same as a reserved keyword, then use backticks(”) before the name of the variable. For example, var ”break = “hello”. Printing Swift Variable You can print the current value of a variable using the print() function. You can interpolate a variable value by wrapping the name in parentheses and escaping it with a backslash before the opening parenthesis. Example Swift program to print variables. import Foundation // Declaring variables var varA = “Godzilla” var varB = 1000.00 // Displaying constant print(“Value of (varA) is more than (varB) million”) Output Value of Godzilla is more than 1000.0 million Print Page Previous Next Advertisements ”;

Swift – Identity Operators

Swift – Identity Operators ”; Previous Next Identity operators are used to check whether the given constants or variables refer to the same instance or not. These operators are generally used with objects or classes because they are reference types. These operators are different from equality operators. Equality operators check if the two given values are equal to not whereas the identity operators check if the two given variables refer to the same reference or not. Swift supports two types of identity operators − Operator Name Example +=== Identical to Num1 === Num2 !== Not Identical to Num1 !== Num2 Identical to Operator in Swift Identical to “===” operator is used to check whether the given two constants or variables refer to the same instance of the class or not. If yes, then this operator will return true. Otherwise, this operator will return false. This operator compares the reference not the content of the objects. Syntax Following is the syntax of the Identical to operator − myVariable1 === myVariable2 Example Swift program to check if the given variables refer to the same object or not. import Foundation // Class class TutorialsPoint { var empName: String init(empName: String) { self.empName = empName } } // Creating object of TutorialsPoint class let object1 = TutorialsPoint(empName: “Monika”) let object2 = object1 // Checking if both variables refer to the same object or not // Using identical to (===) operator if object1 === object2 { print(“YES! Both object1 and object2 are identical”) } else { print(“NO! Both object1 and object2 are not identical”) } Output YES! Both object1 and object2 are identical Not Identical to Operator in Swift The Not Identical to “!==” operator is used to check whether the given variables do not refer to the same operator or not. If yes, then this operator will return true. Otherwise, it will return false. Syntax Following is the syntax of Not Identical to Operator − myVariable1 !== myVariable2 Example Swift program to check if two variables do not refer to the same object or not using not identical to “!==” operator. import Foundation // Class class Author1 { var bookName: String init(bookName: String) { self.bookName = bookName } } class Author2 { var bookName: String init(bookName: String) { self.bookName = bookName } } // Creating objects let obj1 = Author1(bookName: “Tales of Mumbai”) let obj2 = Author2(bookName: “Right to find”) // Using not identical to (!==) operator if obj1 !== obj2 { print(“They are identically not equal”) } else { print(“They are identically equal”) } Output They are identically not equal Print Page Previous Next Advertisements ”;

Swift – Arithmetic Operators

Swift – Arithmetic Operators ”; Previous Next Arithmetic Operators in Swift Operators are the special symbols provided by the Swift that tell the compiler to perform a specific operation. Swift supports various operators. Among all of these operators arithmetic operators are the most commonly used operators. As the name suggested arithmetic operators are used to perform arithmetic operations like addition, subtraction, multiplication, etc with all numeric data types like integers, float, etc. In Swift, arithmetic operators do not allow their values to overflow by default, if you want this kind of behaviour, then use overflow operators. Swift supports the following arithmetic operators − Operator Name Example + Addition 20 + 30 = 50 – Subtraction 30 – 4 = 26 * Multiplication 3 * 4 = 12 / Division 12 / 6 = 2 % Remainder or Modulus 12 % 2 = 0 Addition Operator in Swift The addition operator is used to add the value of two variables. Or we can say that it is used to add two operands of any data type(such as integer, float, etc.). It is also used to concatenate two or more strings into a single string. Syntax Following is the syntax of the addition operator − var result = value1 + value2 Example Swift program to perform addition between numeric variables using addition operator (+). import Foundation // Double data type let num1 = 45.3 let num2 = 23.5 // Using addition operator var result1 = num1 + num2 print(“Sum of (num1) and (num2) is (result1)”) // Integer data type let num3 = 45 let num4 = 12 // Using addition operator var result2 = num3 + num4 print(“Sum of (num3) and (num4) is (result2)”) Output Sum of 45.3 and 23.5 is 68.8 Sum of 45 and 12 is 57 Example Swift program to perform concatenation using addition operator (+). import Foundation let str1 = “Swift” let str2 = “Programming” // Concatenating two strings // Using addition operator var result = str1 + str2 print(result) Output SwiftProgramming Subtraction Operator in Swift Subtraction operation is used to subtract the value of one variable from another. Or we can say that it is used to perform subtraction between two operands. Syntax Following is the syntax of the subtraction operator − var result = value1 – value2 Example Swift program to perform a subtraction between variables using subtract operator “-“. import Foundation // Double data type let num1 = 25.8 let num2 = 12.4 // Using the subtraction operator var result1 = num1 – num2 print(“Subtract (num1) from (num2) = (result1)”) // Integer data type let num3 = 26 let num4 = 17 // Using the subtraction operator var result2 = num3 – num4 print(“Subtract (num3) from (num4) = (result2)”) Output Subtract 25.8 from 12.4 = 13.4 Subtract 26 from 17 = 9 Division Operator in Swift A division operator is used to divide the value of the first variable from another. In other words, the division operator is used to perform division between two operands. This operator works only with numeric values. Syntax Following is the syntax of the division operator − var result = value1 / value2 Example Swift program to perform a division between variables using division operator (/). import Foundation // Double data type let num1 = 34.5 let num2 = 3.2 // Using division operator var result1 = num1 / num2 print(“Divide (num1) by (num2) = (result1)”) // Integer data type let num3 = 14 let num4 = 7 // Using division operator var result2 = num3 / num4 print(“Divide (num3) by (num4) = (result2)”) Output Divide 34.5 by 3.2 = 10.78125 Divide 14 by 7 = 2 Multiplication Operator in Swift A multiplication operator is used to multiply a numeric variable by another numeric variable. In other words, the multiplication operator is used to perform multiplication between two operands. Syntax Following is the syntax of the division operator − var result = value1 * value2 Example Swift program to perform a multiplication between variables using multiply operator (*). import Foundation // Double data type let num1 = 34.5 let num2 = 3.2 // Using the multiplication operator var result1 = num1 * num2 print(“Multiply (num1) by (num2) = (result1)”) // Integer data type let num3 = 14 let num4 = 2 // Using multiplication operator var result2 = num3 * num4 print(“Multiply (num3) by (num4) = (result2)”) Output Multiply 34.5 by 3.2 = 110.4 Multiply 14 by 2 = 28 Remainder Operator in Swift The remainder operator is used to find the remainder left after dividing the values of two numeric variables. It is also known as a modulo operator. It always ignores the negative sign of the second variable or operand, which means the result of x % y and x % -y is always the same. Whereas the result of -x % y and x % y is always different. Syntax Following is the syntax of the remainder operator − var result = value1 % value2 Example Swift program to calculate remainder between variables using remainder operator (%). import Foundation // Double data type let num1 = -18 let num2 = 7 // Finding remainder var result1

Swift – Basic Syntax

Swift – Basic Syntax ”; Previous Next If the Swift is installed successfully it will show the latest version of Swift. Swift is a powerful and expressive language to develop applications for Apple’s devices. It is designed to be easy to read, write and maintain. It also supports object-oriented and functional programming paradigms. Syntax Its syntaxes are much more clear, concise and easy to read. Now let us now see the basic structure of a Swift program, so that it will be easy for you to understand the basic building blocks of the Swift programming language. /* My first Swift program */ var myString = “Hello, World!” print(myString) Following is the output of the above program − Hello, World! Now let us learn what are the basic syntaxes and how you can use them in your Swift program. Import Statement You can use the import statement to import any Objective-C framework or C library) or Swift library directly into your Swift program. For example, the import cocoa statement makes all Cocoa libraries, APIs, and runtimes that form the development layer for all of OS X, available in Swift. Cocoa is implemented in Objective-C, which is a superset of C, so it is easy to mix C and even C++ into your Swift applications. Syntax Following is the syntax of the import statement − import frameworkName or LibraryName Example import Foundation Tokens A Swift program consists of various tokens. A token is the smallest unit of the program which is used to build the blocks of Swift programs. They can be either a keyword, an identifier, a constant, a string literal, or a symbol. Example Swift program to demonstrate the use of tokens. Here the program contains 10 tokens such as import, Foundation, var, myString, etc. import Foundation var myString = 34 print(myString) Output 34 Semicolons In Swift, semicolons after each statement are optional. It is totally up to your choice whether you want or not to type a semicolon (;) after each statement in your code, the compiler does not complain about it. However, if you are using multiple statements in the same line, then it is required to use a semicolon as a delimiter, otherwise, the compiler will raise a syntax error. Example Swift program to demonstrate the use of semicolons in a single line. // Separating multiple statements using semicolon var myString = “Hello, World!”; print(myString) Output Hello, World! Identifiers A Swift identifier is a name used to identify a variable, function, or any other user-defined item. An identifier name must start with the alphabet A to Z or a to z or an underscore _ followed by zero or more letters, underscores, and digits (0 to 9). Swift does not allow special characters such as @, $, and % within identifiers. Swift is a case-sensitive programming language, so Manpower and manpower are two different identifiers in Swift. Example Following are some valid identifiers in Swift − Azad zara abc move_name a_123 myname50 _temp j a23b9 retVal Keywords Keywords are the special pre-defined words available in Swift that have some special meaning and functionality. They are also known as reserved words. These reserved words may not be used as constants, variables or any other identifier names unless they”re escaped with backticks(`). For example, class is not a valid identifier, but `class` is valid. They are commonly designed to define the structure and behaviour of the programs. Swift supports the following keywords − Keywords used in declarations The following are Keywords used in declarations Class deinit Enum extension Func import Init internal Let operator private protocol public static struct subscript typealias var Keywords used in statements The following are Keywords used in statements break case continue default do else fallthrough for if in return switch where while Keywords used in expressions and types The following are Keywords used in expressions and types as dynamicType false is nil self Self super true _COLUMN_ _FILE_ _FUNCTION_ _LINE_ Keywords used in particular contexts The following are Keywords used in particular contexts associativity convenience dynamic didSet final get infix inout lazy left mutating none nonmutating optional override postfix precedence prefix Protocol required right set Type unowned weak willSet Whitespaces Whitespace is the term used in Swift to describe blanks, tabs, newline characters, and comments. Whitespaces separate one part of a statement from another and enable the compiler to identify where one element in a statement, such as int, ends and the next element begins. Therefore, in the following statement − var age There must be at least one whitespace character (usually a space) between var and age for the compiler to be able to distinguish them. On the other hand, in the following statement: //Get the total fruits int fruit = apples + oranges No whitespace

Swift – Arithmetic Overflow Operators

Swift – Arithmetic Overflow Operators ”; Previous Next Arithmetic overflow operators are the special type of operators that are used to perform arithmetic operations on integer types and handle overflow very efficiently. They are generally used when we want to perform calculations that may exceed the maximum or minimum bound of the given integer. For example, we are adding two integers of Int8 type which exceed the maximum bound of the Int8(-128 to 127). So if we are using the normal addition operator “+” we will get an error because we are not allowed to store numbers greater than the maximum or minimum bound in Int8 but using arithmetic overflow operators we can easily overflow the minimum and maximum bound of Int8 without any error. Swift supports three types of arithmetic overflow operators − Operator Name Example &+ Overflow Addition X &+ Y &- Overflow Subtraction X &- Y &* Overflow Multiplication X &* Y Overflow Value Before understanding the workings of the overflow operators, we first understand what overflow value is. As we know an integer has a particular range with minimum and maximum values such as Int8 can store values from -128 to 127. So the overflow value represents the value that exceeds the minimum or maximum range of the given integer. This generally happens when we work with overflow arithmetic operators. We can overflow signed and unsigned integers. When we overflow in a positive direction it will wrap around from the maximum valid integer value to the minimum whereas when we overflow in a negative direction it will wrap around from the minimum valid integer value to the maximum. Example var num = UInt8.max num = num &+ 1 Here an unsigned integer is flowing in the positive direction with the help of the &+ operator because the maximum value of UInt8 is 255 or the binary representation is 11111111. Now we add 1 to num which will exceed its maximum value. So this overflow is handled by wrapping around the minimum representable value of UInt8 which is 0. Overflow Addition “&+” in Swift The overflow Addition “&+” operator is used to add two integers with overflow checking. If any overflow occurs, then it will handle it properly without causing an error to the program. This operator can work with both signed and unsigned integers. Syntax Following is the syntax of the overflow addition operator − var value = x &+ b Example Swift program to calculate the sum of two integers of Int8 types. import Foundation // Defining integer data type let num1 : Int8 = 110 let num2 : Int8 = 30 // Calculate the sum using the normal addition operator var sum = num1 + num2 print(“Sum of (num1) and (num2) = (sum)”) Output Stack dump: 0. Program arguments: /opt/swift/bin/swift-frontend -frontend -interpret main.swift -disable-objc-interop -color-diagnostics -new-driver-path /opt/swift/bin/swift-driver -empty-abi-descriptor -resource-dir /opt/swift/lib/swift -module-name main 1. Swift version 5.7.3 (swift-5.7.3-RELEASE) 2. Compiling with the current language version 3. While running user code “main.swift” Stack dump without symbol names (ensure you have llvm-symbolizer in your PATH or set the environment var `LLVM_SYMBOLIZER_PATH` to point to it): /opt/swift/bin/swift-frontend(+0x551a103)[0x55731fee8103] /opt/swift/bin/swift-frontend(+0x551802e)[0x55731fee602e] /opt/swift/bin/swift-frontend(+0x551a48a)[0x55731fee848a] /lib/x86_64-linux-gnu/libc.so.6(+0x42520)[0x7f138af33520] [0x7f1389bea35f] /opt/swift/bin/swift-frontend(+0x1940b3d)[0x55731c30eb3d] /opt/swift/bin/swift-frontend(+0xc74db9)[0x55731b642db9] /opt/swift/bin/swift-frontend(+0xa454c6)[0x55731b4134c6] /opt/swift/bin/swift-frontend(+0xa419b6)[0x55731b40f9b6] /opt/swift/bin/swift-frontend(+0xa410a7)[0x55731b40f0a7] /opt/swift/bin/swift-frontend(+0xa4341e)[0x55731b41141e] /opt/swift/bin/swift-frontend(+0xa4273d)[0x55731b41073d] /opt/swift/bin/swift-frontend(+0x914a39)[0x55731b2e2a39] /lib/x86_64-linux-gnu/libc.so.6(+0x29d90)[0x7f138af1ad90] /lib/x86_64-linux-gnu/libc.so.6(__libc_start_main+0x80)[0x7f138af1ae40] /opt/swift/bin/swift-frontend(+0x914295)[0x55731b2e2295] Illegal instruction (core dumped) But we got an error because the resultant value will exceed the maximum bound of Int8. So to overcome this problem we will use the addition overflow operator “&+”. This operator will add them without giving an error. import Foundation // Defining integer data type let num1 : Int8 = 110 let num2 : Int8 = 30 // Calculate the sum using the addition overflow operator var sum = num1 &+ num2 print(“Sum of (num1) and (num2) = (sum)”) Output Sum of 110 and 30 = -116 Overflow Subtraction “&-” in Swift The overflow Addition “&-” operator is used to subtract two integers with overflow checking. If any overflow occurs, then it will handle it properly without causing an error. It works with both signed and unsigned integers. Syntax Following is the syntax of the overflow subtraction operator − var value = x &- b Example Swift program to subtract two unsigned integers. import Foundation // Defining unsigned integer data type let num1 : UInt8 = 54 let num2 : UInt8 = 90 // Subtract integers using the normal subtraction operator var sum = num1 – num2 print(“(num1) – (num2) = (sum)”) Output Stack dump: 0. Program arguments: /opt/swift/bin/swift-frontend -frontend -interpret main.swift -disable-objc-interop -color-diagnostics -new-driver-path /opt/swift/bin/swift-driver -empty-abi-descriptor -resource-dir /opt/swift/lib/swift -module-name main 1. Swift version 5.7.3 (swift-5.7.3-RELEASE) 2. Compiling with the current language version 3. While running user code “main.swift” Stack dump without symbol names (ensure you have llvm-symbolizer in your PATH or set the environment var `LLVM_SYMBOLIZER_PATH` to point to it): /opt/swift/bin/swift-frontend(+0x551a103)[0x55736aebe103] /opt/swift/bin/swift-frontend(+0x551802e)[0x55736aebc02e] /opt/swift/bin/swift-frontend(+0x551a48a)[0x55736aebe48a] /lib/x86_64-linux-gnu/libc.so.6(+0x42520)[0x7f575ce12520] [0x7f575bac936c] /opt/swift/bin/swift-frontend(+0x1940b3d)[0x5573672e4b3d] /opt/swift/bin/swift-frontend(+0xc74db9)[0x557366618db9] /opt/swift/bin/swift-frontend(+0xa454c6)[0x5573663e94c6] /opt/swift/bin/swift-frontend(+0xa419b6)[0x5573663e59b6] /opt/swift/bin/swift-frontend(+0xa410a7)[0x5573663e50a7] /opt/swift/bin/swift-frontend(+0xa4341e)[0x5573663e741e] /opt/swift/bin/swift-frontend(+0xa4273d)[0x5573663e673d] /opt/swift/bin/swift-frontend(+0x914a39)[0x5573662b8a39] /lib/x86_64-linux-gnu/libc.so.6(+0x29d90)[0x7f575cdf9d90] /lib/x86_64-linux-gnu/libc.so.6(__libc_start_main+0x80)[0x7f575cdf9e40] /opt/swift/bin/swift-frontend(+0x914295)[0x5573662b8295] Illegal instruction (core dumped) Similarly, we got an error because it exceeded the bound. So to subtract two unsigned integers we will use the subtraction overflow “&-” operator which will subtract them even if their bound exceeds without giving any error. import Foundation // Defining unsigned integer data type let num1 : UInt8 = 54 let num2 : UInt8 = 90 // Subtract integers using the subtraction overflow operator var sum = num1 &- num2 print(“(num1) – (num2) = (sum)”) Output 54 – 90 = 220 Overflow Multiplication(&*) in Swift The overflow Multiplication “&*” operator is used to find the product

Swift – Assignment Operators

Swift – Assignment Operators ”; Previous Next Assignment Operators are the special operators. They are used to assign or update values to a variable or constant. In the assignment operators, the right-hand side of the assignment operator is the value and the left-hand side of the assignment operator should be the variable to which the value will be assigned. The data type of both sides should be the same, if they are different we will get an error. The associativity of assignment operators is from right to left. Swift supports two types of assignment operators − Simple Assignment Operator − It is the most commonly used operator in Swift. It is used to assign value to a variable or constant. Compound Assignment Operators − They are the combination of assignment operator (=) with other operators like +, *, /, etc. The following table shows all the assignment operators supported by Swift − Operators Name Example (=) Assignment var x = 10 += Add and Assignment A += B is equivalent to A = A + B -= Subtract and Assignment A -= B is equivalent to A = A – B *= Multiply and Assignment A *= B is equivalent to A = A * B /= Divide and Assignment A /= B is equivalent to A = A / B %= Modulo and Assignment A %= B is equivalent to A = A % B &= Bitwise AND and Assignment A &= B is equivalent to A = A & B |= Bitwise Inclusive OR and Assignment A += B is equivalent to A = A | B ^= Bitwise Exclusive OR and Assignment A ^= B is equivalent to A = A ^B <<= Left Shift and Assignment A <<= B is equivalent to A = A << B >>= Right Shift and Assignment A >>= B is equivalent to A = A >> B Assignment Operator in Swift An assignment operator “=” is the most straightforward and commonly used operator in Swift. It is used to assign value to a constant or variable. The left-hand side of the assignment operator contains the variable name and the right-hand side contains the value. While using the assignment operator always remember the data type of both the operands should be the same. Syntax Following is the syntax of the assignment operator − var number = 10 Example Swift program to assign a string to a variable. import Foundation // Defining a variable of string type let mystring : String // Assigning a value to the variable using the assignment operator mystring = “Tutorialspoint” // displaying result print(“String = “, mystring) Output String = Tutorialspoint Add and Assignment Operator in Swift An Add and Assignment Operator “+=” is used to perform addition between the left variable and right variable and then assign the result to the left variable. Suppose we have two variables A = 10 and B = 20. A += B => A = 10 + 20 => A = 30. Syntax Following is the syntax of the add and assignment operator − X += Y Example Swift program to find the sum of two variables using add and assignment operator “+=”. import Foundation var num1 = 10 var num2 = 80 // Calculating sum num1 += num2 print(“Sum = “, num1) Output Sum = 90 Subtract and Assignment Operator in Swift A Subtract and Assignment Operator “-=” is used to perform a subtraction between the left variable and the right variable and then assign the result to the left variable. Suppose we have two variables A = 10 and B = 20. A -= B => A = 10 – 20 => A = -10. Syntax Following is the syntax of the subtract and assignment operator − X -= Y Example Swift program to subtract two variables using subtract and assignment operator “-=”. import Foundation var num1 = 34 var num2 = 21 // Subtracting num1 from num2 num1 -= num2 print(“Result = “, num1) Output Result = 13 Multiply and Assignment Operator in Swift A Multiply and Assignment Operator “*=” is used to perform a multiplication between the left operand and the right operand and then assign the result to the left operand. Suppose we have two variables A = 10 and B = 20. A *= B => A = 10 * 20 => A = 200. Syntax Following is the syntax of the multiply and assignment operator − X *= Y Example Swift program to find the product of two variables using multiply and assignment operator “*=”. import Foundation var num1 = 12 var num2 = 2 // Product of two numbers num1 *= num2 print(“Result = “, num1) Output Result = 24 Divide and Assignment Operator in Swift A Divide and Assignment Operator “/=” is used to divide the left operand by the right operand and then assign the result to the left operand. Suppose we have two variables A = 20 and B = 5. A /= B => A = 20 / 5 => A = 4. Syntax Following is the syntax of the divide and assignment operator − X

Solidity – Arrays

Solidity – Arrays ”; Previous Next Array is a data structure, which stores a fixed-size sequential collection of elements of the same type. An array is used to store a collection of data, but it is often more useful to think of an array as a collection of variables of the same type. Instead of declaring individual variables, such as number0, number1, …, and number99, you declare one array variable such as numbers and use numbers[0], numbers[1], and …, numbers[99] to represent individual variables. A specific element in an array is accessed by an index. In Solidity, an array can be of compile-time fixed size or of dynamic size. For storage array, it can have different types of elements as well. In case of memory array, element type can not be mapping and in case it is to be used as function parameter then element type should be an ABI type. All arrays consist of contiguous memory locations. The lowest address corresponds to the first element and the highest address to the last element. Declaring Arrays To declare an array of fixed size in Solidity, the programmer specifies the type of the elements and the number of elements required by an array as follows − type arrayName [ arraySize ]; This is called a single-dimension array. The arraySize must be an integer constant greater than zero and type can be any valid Solidity data type. For example, to declare a 10-element array called balance of type uint, use this statement − uint balance[10]; To declare an array of dynamic size in Solidity, the programmer specifies the type of the elements as follows − type[] arrayName; Initializing Arrays You can initialize Solidity array elements either one by one or using a single statement as follows − uint balance[3] = [1, 2, 3]; The number of values between braces [ ] can not be larger than the number of elements that we declare for the array between square brackets [ ]. Following is an example to assign a single element of the array − If you omit the size of the array, an array just big enough to hold the initialization is created. Therefore, if you write − uint balance[] = [1, 2, 3]; You will create exactly the same array as you did in the previous example. balance[2] = 5; The above statement assigns element number 3rd in the array a value of 5. Creating dynamic memory arrays Dynamic memory arrays are created using new keyword. uint size = 3; uint balance[] = new uint[](size); Accessing Array Elements An element is accessed by indexing the array name. This is done by placing the index of the element within square brackets after the name of the array. For example − uint salary = balance[2]; The above statement will take 3rd element from the array and assign the value to salary variable. Following is an example, which will use all the above-mentioned three concepts viz. declaration, assignment and accessing arrays − Members length − length returns the size of the array. length can be used to change the size of dynamic array be setting it. push − push allows to append an element to a dynamic storage array at the end. It returns the new length of the array. Example Try the following code to understand how the arrays works in Solidity. pragma solidity ^0.5.0; contract test { function testArray() public pure{ uint len = 7; //dynamic array uint[] memory a = new uint[](7); //bytes is same as byte[] bytes memory b = new bytes(len); assert(a.length == 7); assert(b.length == len); //access array variable a[6] = 8; //test array variable assert(a[6] == 8); //static array uint[3] memory c = [uint(1) , 2, 3]; assert(c.length == 3); } } Print Page Previous Next Advertisements ”;