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 – Home

Swift Tutorial Table of content Swift Tutorial What is Swift Programming Language? Why to Learn Swift? Swift Jobs and Opportunities Swift Online Compiler Careers with Swift Who Should Learn Swift Prerequisites to Learn Swift Frequently Asked Questions about Swift PDF Version Quick Guide Resources Job Search Discussion Swift Tutorial Swift is a new programming language developed by Apple Inc. for iOS and OS X development. It adopts the best of C and Objective-C, without the constraints of C compatibility. It uses the same runtime as the existing Obj-C system on Mac OS and iOS, which enables Swift programs to run on many existing iOS and OS X platforms. This Swift tutorial will help you to understand Swift in a very easy and simple way. So that you can create your own Swift application or program. It will cover all the major concepts of Swift programming language which will boost your confidence and make you a good Swift programmer. What is Swift Programming Language? Swift is a modern and open-source programming language that is specifically designed by Apple for its platforms. It was introduced in 2014 with the aim of providing a language that is not only powerful and versatile but also provides great safety, performance, interoperability with Objective-C and modern syntax. So using Swift developers can easily develop robust and high-performance applications. The latest version of Swift is Swift 5.9.2 We can also use swift to develop software for phones, desktops, and servers. Swift is a great combination of modern thinking and diverse contributions from its open-source community. The Swift compiler is optimized for its performance and the language itself is tailored for its development. Why to Learn Swift? If you are interested in developing an application for Apple’s ecosystem, then Swift is for you. Swift opens a gateway for you to create dynamic, innovative, and powerful applications for iOS, macOS, watchOS, and tvOS. Apple prefers Swift programming language as a primary language because it has modern syntax, high performance, provides great safety, and works seamlessly with all devices. We can also use Swift to create applications for Windows and Android due to its open-source nature and cross-platform compatibility. Cross-platform app development allows developers to write code and then deploy it on multiple platforms, for example, Flutter, React Native, and Xamarin. However Swift offers this versatility, the user experience may not be as seamless as that can achieved by using other programming languages such as C#, .Net, Java, Kotlin etc. Swift Jobs and Opportunities In the dynamic era of technology, Swift programming language emerged as a milestone for creating user-friendly applications for Apple’s products. The demand for Swift”s expertise is reaching to new heights and the market is loaded with lots of opportunities for talented developers. Whether you are a seasoned Swift developer or a newcomer you will have lots of opportunities with good packages. The average salary of a Swift developer is 5L to 12L per year, it can vary depending on the location, position and experience. There are so many companies that provide a good package and working culture for Swift developers. It”s impossible to list down all the company names that use Swift, but some Apple Google Facebook Microsoft Amazon Twitter Airbnb Snapchat Adobe Pinterest Slack Uber Netflix Swift Online Compiler We have provided Swift Online Compiler/Interpreter which helps you to Edit and Execute the code directly from your browser. Example // First Swift program print(“Hello! Swift”) Output Hello! Swift Careers with Swift Swift is a powerful and intuitive language for software development. It provides a robust platform for creating dynamic and effective applications for Apple’s ecosystem. It is commonly used to create seamless and innovative applications for iOS, macOS, watchOS and tvOS. Swift opens the doors for huge opportunities where the developer can show off his/her skills. Following are some potential career options with Swift programming language − iOS/macOS App Developer Mobile App Developer Game developer Augmented Reality(AR) developer UI/UX designer for iOS app Quality Assurance(QA) engineer for iOS App iOS Framework Developer Swift Trainer Swift Technical Writer Cross-Platform Mobile Developer Full Stack Swift Developer WatchOS App Developer Who Should Learn Swift This tutorial is designed for software programmers who would like to learn the basics of Swift programming language from scratch. This tutorial will give you enough understanding of Swift programming language that you can take yourself to higher levels of expertise. Prerequisites to Learn Swift Before proceeding with this tutorial, you should have a basic understanding of Computer Programming terminologies and exposure to any programming language. Frequently Asked Questions about Swift There are some very Frequently Asked Questions(FAQ) about Swift, this section tries to answer them briefly. What is the latest version of Swift? The latest version of Swift is Swift 5.9. It was released in September 2023 with new features like a macros system, generic parameters packs, ownership packs, and if and switch as expressions. How do you say hello in Swift? In Swift programming, we can say hello using the print() function. Simply write print(“Hello world”) and run this code in the compiler it will print “Hello world” on the screen without creating any extra variable. What Is Swift Used For? Swift is a powerful and general programming language that is used to develop applications for iPhones, iPads, MacOS desktops, Apple Watches and TVs. It can also run on Linux and Windows operating systems. What

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

Swift – Misc Operators

Swift – Misc Operators ”; Previous Next Miscellaneous Operators Swift Swift supports different types of operators like arithmetic, comparison, logical, bitwise, assignment and range operators. Apart from these operators it has miscellaneous operators are they are − Operator Name Example – Unary Minus -23 + Unary Plus 32 Condition ? X : Y Ternary operator X>Y ? 43 : 21= 43 Unary Minus Operator in Swift A unary minus operator is used to represent a negative(-) sign that is placed before the numeric value. It converts a positive number into a negative and a negative number into a positive. It is a prefix operator, which means it is placed before the value without any white space. Syntax Following is the syntax of the unary minus operator − -x Example Swift program to find the sum of two numbers using the unary minus operator. import Foundation let x = 23 // Specifying sign using unary minus operator let y = -2 var sum = 0 sum = x + y // 23 + (-2) print(“Sum of (x) and (y) = (sum)”) Output Sum of 23 and -2 = 21 Unary Plus Operator in Swift A unary plus operator is used to make a numeric expression positive. It only adds a positive (+) sign before the numeric value but does not change the value. It is also a prefix operator. Syntax Following is the syntax of the unary plus operator − +x Example Swift program to find the sum of two numbers using the unary plus operator. import Foundation let x = 20 // Specifying sign using unary plus operator let y = +2 var sum = 0 sum = x + y // 23 + (+2) print(“Sum of (x) and (y) = (sum)”) Output Sum of 20 and 2 = 22 Ternary Conditional Operator in Swift A ternary conditional operator is a shorthand of an if-else statement. It has three parts: condition ? expression1 : espression2. It is the most effective way to decide between two expressions. Because it evaluates one of the two given expressions according to whether the given condition is true or false. If the given condition is true, then it evaluates expression1. Otherwise, it will evaluate expression2. Syntax Following is the syntax of the ternary conditional operator − Condition ? Expression1 : Expression2 Example Swift program to explain ternary conditional operator. import Foundation let x = 20 let y = 2 // If x is greater than y then it will return 34 // Otherwise return 56 var result = x > y ? 34 : 56 print(result) Output 34 swift_operators.htm Print Page Previous Next Advertisements ”;

Swift – Operators

Swift – Operators ”; Previous Next What is an Operator in Swift? An operator is a symbol that tells the compiler to perform specific mathematical or logical manipulations. Or we can say that operators are special symbols that are used to perform specific operations between one or more operands. For example, to add two numbers such as 34 and 21 we will use the + operator (34 + 21 = 55). Type of Operators in Swift Swift supports the following types of operators − Arithmetic Operators Comparison Operators Logical Operators Bitwise Operators Assignment Operators Range Operators Misc Operators Let”s discuss each operator separately in detail. Swift Arithmetic Operators Arithmetic operators are used to perform mathematic operations like addition, division, multiplication, etc. on the given operands. They always work on two operands but the type of these operands should be the same. Swift supports the following arithmetic operators − Operator Name Example + Addition 20 + 30 = 50 – Subtraction 30 – 10 = 20 * Multiplication 10 * 10 = 100 / Division 20 / 5 = 4 % Modulus 10 % 2 = 0 Swift Comparison Operators Comparison operators are used to compare two operands and find the relationship between them. They return the result into a boolean(either true or false). Swift supports the following comparison operators − Operator Name Example (==) Equal 10 == 10 = true != Not Equal 34 != 30 = true > Greater than 90 > 34 = true < Less than 12 < 34 = true >= Greater than or Equal to 30 >= 10 = true <= Less than or Equal to 10 <= 32 = true Swift Logical Operators Logical operators are used to perform logical operations between the given expressions. It can also make decisions on multiple conditions. It generally works with Boolean values. Swift supports the following logical operators − Operator Name Example && Logical AND X && Y || Logical OR X || Y ! Logical NOT !X Swift Bitwise Operators Bitwise operators are used to manipulate individual bits of the integer. They are commonly used to perform bit-level operations. Swift supports the following bitwise operators − Operator Name Example & Bitwise AND X & Y | Bitwise OR X | Y ^ Bitwise XOR X ^ Y ~ Bitwise NOT ~X << Left Shift X << Y >> Right Shift X >> Y Swift Assignment Operators Assignment operators are used to assign and update the value of the given variable with the new value. Swift supports the following assignment operators − Operator Name Example (=) Assignment X = 10 += Assignment Add X = X + 12 -= Assignment Subtract X = X – 12 *= Assignment Multiply X = X * 12 /= Assignment Divide X = X / 12 %= Assignment Modulus X = X % 12 <<= Assignment Left Shift X = X << 12 >>= Assignment Right Shift X = X >> 12 &= Bitwise AND Assignment X = X & 12 ^= Bitwise Exclusive OR Assignment X = X ^12 |= Bitwise Inclusive OR Assignment X = X | 12 Swift Misc Operators Apart from the general operators Swift also supports some special operators and they are − Operator Name Example – Unary Minus -9 + Unary Plus 2 Condition ? X : Y Ternary Conditional If Condition is true ? Then value X : Otherwise value Y Swift Advance Operators Apart from the basic operators Swift also provides some advanced operators that are used to manipulate complex values and they are − Arithmetic Overflow Operators Identity Operators Identity Operators Let”s discuss each operator separately in detail. Swift Arithmetic Overflow Operators Arithmetic overflow operators are used to perform arithmetic operations and handle overflow very well if occurs. Or we can say that arithmetic operators work with those integers whose value may exceed the maximum or minimum bound. Swift supports the following arithmetic overflow operators − Operator Name Example &+ Overflow Addition Num1 &+ Num2 &- Overflow Subtraction Num1 &- Num2 &* Overflow Multiplication Num1 &* Num2 Swift Identity Operators Identity operators are used to determine whether the given variable refers to the same instance or not. These operators work with objects and classes. They are referenced type operators.