top

Search

Swift Tutorial

It has become custom and tradition to use the Hello World program to learn any new language. We will also begin with the Hello World program in Swift to learn basic syntax. Let’s try to understand basic syntax by looking at the below program: import Cocoa var str ="Hello World!" println(str)Output: Hello  World!The above code contains a declaration that imports cocoa, which makes the development layer for all Cocoa libraries and APIs, accessible in swift together with execution times. The above-mentioned library is used in Objective-C (C linguistic superset). The same program will include the import of UIKit if we generate the iOS playground program. The program looks like−. import UIKit var str = "Hello World!" println(str)Let us see the fundamental structure of a program in Swift, so we can easily comprehend the fundamental components of the Swift language programming. Import in Swiftimport CocoaWe can import an Objective-C structure (or C library) from our Swift program straight via the import declaration. For instance, all Cocoa libraries, APIs, and runtimes forming the development layer in all OS X are made accessible in Swift by Import Cocoa Statement. 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 Token in SwiftThere are several tokens in a Swift program and a token is either a keyword, an identifier, a constant, a literal string or a symbol. For instance, three tokens comprise the following Swift  declaration: print("Hello!") The individual tokens are: Print “ !Comments in SwiftComments are the Swift program lines that will not be compiled at the time of compilation by the Swift compiler. They serve to help programmers comprehend the snippet's working and the compiler ignores them. Multiline comments begin with /* and end with* / and we write remarks between them. import UIKit  /* This is the comment section */ var str ="Hello World" println(str) Multiline comments can be used as shown below : /* My first program in Swift! Hello, World */Single line comments can be written using a double slash.// Hello World /* This is another comment :: end of code */SemiColonSwift does not require you to write a semicolon(;), although it is optional after each declaration in your software. If you are using a semicolon the compiler does not complain. However, you need to use a semicolon as a delimiter when using various statements within the same row, otherwise, the compiler will increase the syntax error.  /* My first program in Swift  */ var myString ="Hello, World!";print(myString)IdentifiersThe identifier is used to define a variable, function, or other item defined by the user. Identification begins with an A-to-Z alphabet or a z-followed by zero or more letters, underlines, and figures (0-9).Special characters such as @, $ and % in the identifier cannot be allowed by Swift. The Swift programming language is case-sensitive. TEST and test are therefore two distinct Swift identifiers.  For using any reserve term as identifier we can place backtick(')  before and after reserved term. Please find below some acceptable identifiers :Some of the reserved terms in SwiftKeywords Used in DeclarationsClassdeintienum  extensionFuncimportInitInternalLetoperatorprivateprotocolpublicstaticstructsubscripttypealiasvarKeywords Used In StatementsBreakCasecontinuedefaultdoElsefallthroughforifinreturnswitchwherewhileKeywords used in expressions and typesasDynamicTypefalseisnilselfselfsupertrue_COLOUMN__FILE__FUNCTION_LINEKeywords Used in Particular contextsAssociativityConveniencedynamicdidSetfinalgetinfixinoutlazyleftmutatingnonenonmutatingoptionaloverridepostfixprecedenceprefixprotocolrequiredrightsettypeunownedweakwillsetPrinting in SwiftWe have a print keyword to print anything quickly. There are three components in printing. Items – printed itemsSeparator – separator between itemsTerminator – the value with which line should end.Let’s see an example and syntax of the same.Data TypesSwift has inbuilt support for many data types. Swift offers different types of data that enable programmers to set the variable's value by selecting a suitable type. The following are the data types supported by Swift : IntegerAn integer is a whole number, like 42 and -23, which is not fractional. Integrals are either signed or unsigned (positive, zero or negative). In the 8, 16, 32, and 64-bit forms, Swift offers signed and unsigned integers. These entries obey an eight-bit unsigned integer of the form UInt8 and a 32-bit signed integer of the form Int32 following a naming convention such as C. These integer kinds have names capitalized, like all kinds in Swift. The minimum or maximum values of each integer type can also be accessed by the programmers with its minimal and max characteristics:  let minValue= UInt8.min // MinValue equal to 0,  let maxValue= UInts8. max //maxValue equivalent to 255  FloatThis represents a 32-bit floating-point and lower decimal point number. 3.14159, 0.6 and -273.158, for instance. Swift provides two kinds of floating number points programmers.These are: DoubleThis is a floating point number of one single pixel. Programmers need to use it for high or especially accurate floating point values. Float used to be the float point number of a 32-bit system. Programmers do not need 64 bi accuracy when floating dot values. Double has 15 decimal numbers of accuracy, while Float's accuracy can be as few as 6 decimals. The suitable floating point type relies on the form and spectrum of values within your code that you need to operate. Bool: This data type is a Boolean value, which will be  either true or falseCharacter:This is a single character string literal. For example, "A"String: This is a single unit ordered a set of characters. For example, "Hello"Optional: Swift offers another data type where programmers can represent a value or no value variable.Tuples: This data type can group multiple values in a single variable.This is a table that shows the maximum and minimum value that can be stored in such variables:Int81byte-127 to 127UInt81byte0 to 255Int324bytes-2147483648 to 2147483647UInt324bytes0 to 4294967295Int648bytes-9223372036854775808 to 9223372036854775807UInt648bytes0 to 18446744073709551615Float4bytes1.2E-38 to 3.4E+38 (~6 digits)Double8bytes2.3E-308 to 1.7E+308 (~15 digits)Type AliasesYou can use typealias to generate a fresh name for a current type. The easy syntax for defining a fresh type is here:typealias newname = typeThe following line, for instance, tells the compiler that distance is another Int name.typealias Distance = IntNow, this statement is completely legal and produces an integer variable called Feet. typealias Distnace= Int var Feet:Distance= 100 print(Feet)Type SafetySwift is a safe type of language, meaning you can't error pass it on Int if a portion of your code expects a string. Because Swift is safe to type, type checks are carried out when you create your code and any incorrect forms are flagged as mistakes. var varB = 42 varB = "Hello World" print(varB)The above program will generate  below compile-time error: main.swift:2:8: error: cannot assign value of type 'String' to type 'Int'  varB = "Hello World" Type InferenceThis sort of inference allows a compiler to automatically deduce the sort of expression when it compiles your code merely by looking at the values. Swift utilizes inference sort in order to determine the correct type. // varX is inferred to be of type Int  var varX = 60  print(varX) // varY is inferred to be of type Double var varY = 3.14159 print(varY) // varZ is also inferred to be of type Double var varZ = 3+0.14159  print(varZ)VariablesA variable gives us a storage name that can be used by our programs. A variable name cannot contain math, arrow, private use (or invalid) names, or may not start with a number even though numbers may be contained elsewhere in the same name. Each variable in Swift 4 has a particular type that determines the size and design of the memory of the variable, the range of values that could be stored within the memory and the set of activities that could be implemented. Variable declaration in SwiftA variable statement informs the compiler what type, where and how much the storage for the variable should be created. Var keywords are used to make declarations of variables. import Cocoa var firstvar = 78 println(firstvar)The output of the above program would be 78. Type AnnotationWhen declaring a variable, programmers can give an annotation type that is clear on the type of values that can be saved by the specified variable. The overall way variable is used like below : var variableName:<data type>=<optional initial value>Example:import Cocoa var xVar = 76 println (xvar) var yVar:Float  yVar = 3.14159 println (yVar) println(" 1st Value \(varA) 2nd Value \(varB) ")OptionalsSwift also presents an optional type that deals with the lack of value. Either "there is a value, and it is equal tox," or "there is no value" are optional. An optional one is a type alone, one of the fresh super-powered enums of Swift 4. The value, None and Some(T), are two possible values, with T being a related value of the right data type accessible in Swift. Please have a look at the below example for optional int, optional string, and optional no value: var optionalInt: Int? var optionalStr: String? var optionalStr: String? = nilLet’s look at the below example to understand how optional works: var optionalString:String?=nilif optionalString!=nil{ print(optionalString) } else { print("optionalString has nil value") }The output of the above program would be  optionalString has nil valueOptionals are comparable to nil with Objective-C pointers, but operate on any type, not just classes. Forced UnwrappingIf you have optionally defined a variable, then you must unwrap the value from that variable. That only implies the mark at the end of the variable is an exclamation. Let’s try to understand this concept from the below example: Without forced unwrapping var xString:String? xString = "Hello, World!" if xString != nil {  print(xString) } else { print("xString has nil value") } With forced unwrappingvar xString:String? xString = "Hello, World!" if xString != nil{    print(xString!)/*we have used exclamation mark for forced  unwrapping*/  } else {  print("xString has nil value") } The first program output would be Optional("Hello, World!") while the second one will have "Hello, World!"Automatic unwrappingYou can use an exclamation mark instead of a question mark to declare optional variables. These optional variables will automatically unwrap and at the end of the variable, you don't have to use another exclamation mark to get the allocated value. var xString:String! //We have used exclamation mark here. xString = "Hello, World!" if xString != nil{    print(xString)//no need to use exclamation mark } else { print("xString has nil value") }The output would be "Hello, World!"Optional BindingTo find out whether an optional value includes a value, use the optional binding to create it, accessible as a temporary variable. Please have a look at the below syntax to understand  optional binding: if let constantName = someOptional {     statements  } Example:  var xString:String?  xString = "Hello, World!" if let yourString = xString {  print("Your string has - \(yourString)")  } else {  print("Your string does not have a value")  } The output of the above program would be  Your string has - Hello, World! TuplesSwift also presents tuples that are used in a single compound value to group various values. The values can be of any kind in a tuple and do not have to be the same.For instance ("Hello  World", 100) is a two-value multiplex, one of the type strings and another of the type integer. It's a valid syntax. let AuthorizedError = (401, "Not authorized") If a server does not execute anything on the server, it returns two values. Error code, and description. You can generate tuples from any number of values and various data types as you wish. Below is the syntax for tuple declaration: var TupleName = (Value1, value2,… any number of values)Please find below valid tuple declaration:var error401 = (401, “Not authorized”)You can use the index numbers from 0 to access the values of tuples.  print(“The definition of error is\(error401.1)”)You can name tuple variables and call them by their names when you declare them.var error401 = (errorCode: 401, description: “Not authorized”) print(error401.errorCode)   // prints 401. Tuples are useful to return multiple values from functions. Similarly, a web application could return a tuple form ("string," Int) to display whether the load was effective or not. By returning various values in a tuple, we can decide according to several tuple kinds. Tuples are helpful for provisional values and not suitable for complicated information. ConstantsConstants link a name with a value of a particular type (e.g. str, pi num, or welcomeMsg).  A constant's value cannot be changed once it is set, whilst in the future, a variable may be set to a different value. This means constants in the Swift program refer to set values that will not change in the program's execution. You must declare it with the following let keyword before using constants- let constantName = <initial value>This is a straightforward instance of how a constant in Swift should be declared-let constX = 46 print(constX) When the above program is executed, the output would be 46. Type AnnotationsWhen you declare a constant, you can provide a type annotation to show the sort of values the constant can store. The syntax is shown below : var constantName:<data type> = <optional initial value>The below example shows how to use type annotations while writing a program :let constX = 46print(constX) let constY:Float = 3.14159 print(constY) We need to provide initial value while using type annotations. The above program output would be below : 46  3.1415901184082Naming ConstantsThere are letters, numbers and the underscore character for a constant name. A valid constant name can start with a letter or an underscore. Upper and lowercaseletters are different because Swift is case-sensitive. To name your variables, you can use single or Unicode characters. Below are valid constant names: let _const ="Hello, World!" print(_const)let你好="你好世界" print(你好)LiteralsLiteral and constant values play a major role in coping with values within a program in most programming languages. The notion of literals and constants is also supported by Swift. They have a steady value and have a memory place for expressing them in the code. 60                // Integer literal 3.14159           // Floating-point literal "Hello, world!"   // String literalTypes of Literals in SwiftNumeric LiteralsIt has its subcategories as literal integer and floating-point and can be written as follows: A decimal number, with no prefix A binary number, with a 0b prefix An octal number, with a 0o prefix A hexadecimal number, with a 0x prefix All literals above have a decimal value of 17. It should also be noted that literals of floating points can be decimal without a prefix or a prefix of 0x hexadecimal literal. On both sides of the decimal point, they must always have a number. The optional exponent for hexadecimal floats may also contain an upper or lower case letter e and / or upper case, or lowercase letter p. For decimal numbers with an exponent of exp, the base number is multiplied by 10.  For exp: 2.25e2 means 2.25 × 102, or 225.0. 2.25e-2 means 1.25 × 10-2, or 0.0225. For hexadecimal numbers with an exponent of exp, the base number is multiplied by 2exp: 0xFp2 means 25× 22, or 100.0.0xFp-2 means 25× 2-2, or 6.25 String Literals String literal is a series of characters with a double quote beginning(") and a double quote closing(").  "Monday" String literals can have a double quotation("), without escape and a backslash (\) or carry return without escape. In strings literals, unique characters must be used and another branch of strings literals called an escape sequence must be formed, with the specific significance of each escape sequence. The following are:Escape SequenceDescription\0Null character\\character\bBackspace\fForm feed\nNewline\rCarriage return\tHorizontal tab\vVertical tab\'Single Quote\"Double Quote\000Octal number of one to three digits\xhh...Hexadecimal number of one or more digitsThe following example illustrates how to use a few literals −import Cocoa  let str = "Hello\tWorld\n\n\'Swift\'" println(str)If we use the playground to operate the above program then, this outcome is  Hello World 'Swift'OperatorsVarious operators are endorsed by Swift. These symbols are used for logical and mathematical program activities. These symbols combine single constants and variables to shape phrases and execute particular tasks. In this section, you will learn about all the operators supporting Swift's coding programming language. Operators are unique symbols or sentences that are checked, combined or changed by programmers. The multiplication operator (*), for instance, multiplies two numbers. The logical AND operator & &  (as if the user name & & password) and the increased operator++iI are a complicated instance, which can help boost i's value by 1. Swift promotes most conventional C operators and removes several prevalent mistakes in coding.There are three types of operators in swift language: Unary operator: These operators work on a single objective. These operators appear before the operations instantly. Two kinds of single operators are available. It is- Unary prefix (example:a, !value)Unary postfix (example: x++) Binary operator: These operators operate with two objectives (such as 6+ 2), i.e. two operators. Ternary operator: These operators work on three objectives. Swift has only one ternary operator (a ? b : c). Types of Swift operator1. Arithmetic OperatorsOperatorsDescription+Addition-Subtraction*Multiplication/Division%Modulus++Increment−−Decrement2. Assignment OperatorsOperatorsDescription=Assign+=Increments then assign-+Decrements then assign*=Multiplies then assign/=Divides then assigns%=Modulus then assigns3. Comparison OperatorsOperatorsDescription==Is equal to!=Is not equal to>Greater than<Less than>=Greater than or equal to<=Less than or equal to4. Logical OperatorsOperatorsDescription&&And operator. Performs logical conjunction on two expressions(if both expressions evaluate to True, the result is True. If either expression evaluates to False, the result is False)||Or operator. Performs a logical disjunction on two expressions(if either or both expressions evaluate to True, the result is True).!Not operator. It performs logical negation on an expression.5. Bitwise OperatorsOperatorsDescription&Binary AND Operator|Binary OR Operator^Binary XOR Operator<<Binary Left Shift Operator>>Binary Right Shift Operator6. Misc OperatorsThis category is the conditional operator. The structure is: condition? X: Y, if a condition is true? If condition is true? Then first expression: otherwise 2nd expression. All of the above-mentioned operators are also prevalent in C and most C or C++ programmers know the operators.7. Range OperatorsOperatorsDescriptionClosed RangeThis (a...b) defines  range that starts from a up to , and includes the values a and b as well example if the values in between 6 then range includes1, 2, 3, 4,5 and 6Half-Open RangeThis (i..< j) defines i range that starts from me up to j, but does not include j. .< 6 gives 1, 2, 3, 4 and 5Summary:We have got a fair idea of swift keywords and basic syntax with help of this module. This module helped us in understanding the concept of Import, Tokens ,comments,.keywords ,identifiers and different operators used in Scala.
logo

Swift Tutorial

Scala Basics Syntax

It has become custom and tradition to use the Hello World program to learn any new language. We will also begin with the Hello World program in Swift to learn basic syntax. Let’s try to understand basic syntax by looking at the below program: 

import Cocoa
var str ="Hello World!"
println(str)
Output:
Hello  World!

The above code contains a declaration that imports cocoa, which makes the development layer for all Cocoa libraries and APIs, accessible in swift together with execution times. The above-mentioned library is used in Objective-C (C linguistic superset). 

The same program will include the import of UIKit if we generate the iOS playground program. The program looks like−. 

import UIKit
var str = "Hello World!"
println(str)

Let us see the fundamental structure of a program in Swift, so we can easily comprehend the fundamental components of the Swift language programming. 

Import in Swift

import Cocoa

We can import an Objective-C structure (or C library) from our Swift program straight via the import declaration. For instance, all Cocoa libraries, APIs, and runtimes forming the development layer in all OS X are made accessible in Swift by Import Cocoa Statement. 

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 

Token in Swift

There are several tokens in a Swift program and a token is either a keyword, an identifier, a constant, a literal string or a symbol. For instance, three tokens comprise the following Swift  declaration: 

print("Hello!")
The individual tokens are:
Print “ !

Comments in Swift

Comments are the Swift program lines that will not be compiled at the time of compilation by the Swift compiler. They serve to help programmers comprehend the snippet's working and the compiler ignores them. Multiline comments begin with /* and end with* / and we write remarks between them. 

import UIKit 
/* This is the comment section */ 
var str ="Hello World"
println(str) 

Multiline comments can be used as shown below : 

/* My first program in Swift!
Hello, World */

Single line comments can be written using a double slash.

// Hello World
/* This is another comment :: end of code */

SemiColon

Swift does not require you to write a semicolon(;), although it is optional after each declaration in your software. If you are using a semicolon the compiler does not complain. However, you need to use a semicolon as a delimiter when using various statements within the same row, otherwise, the compiler will increase the syntax error.  

/* My first program in Swift  */
var myString ="Hello, World!";print(myString)

Identifiers

The identifier is used to define a variable, function, or other item defined by the user. Identification begins with an A-to-Z alphabet or a z-followed by zero or more letters, underlines, and figures (0-9).Special characters such as @, $ and % in the identifier cannot be allowed by Swift. The Swift programming language is case-sensitive. TEST and test are therefore two distinct Swift identifiers.  For using any reserve term as identifier we can place backtick(')  before and after reserved term. Please find below some acceptable identifiers :

Some of the reserved terms in Swift

Keywords Used in Declarations



Classdeintienum  extension
FuncimportInitInternal
Letoperatorprivateprotocol
publicstaticstructsubscript
typealiasvar


Keywords Used In Statements



BreakCasecontinuedefault
doElsefallthroughfor
ifinreturnswitch
wherewhile


Keywords used in expressions and types



asDynamicTypefalseis
nilselfselfsuper
true_COLOUMN__FILE__FUNCTION_
LINE



Keywords Used in Particular contexts



AssociativityConveniencedynamicdidSet
finalgetinfixinout
lazyleftmutatingnone
nonmutatingoptionaloverridepostfix
precedenceprefixprotocolrequired
rightsettypeunowned
weakwillset

Printing in Swift

We have a print keyword to print anything quicklyThere are three components in printing. 

  • Items – printed items
  • Separator – separator between items
  • Terminator – the value with which line should end.

Let’s see an example and syntax of the same.

Data Types

Swift has inbuilt support for many data types. Swift offers different types of data that enable programmers to set the variable's value by selecting a suitable type. The following are the data types supported by Swift : 

Integer

An integer is a whole number, like 42 and -23, which is not fractional. Integrals are either signed or unsigned (positive, zero or negative). In the 8, 16, 32, and 64-bit forms, Swift offers signed and unsigned integers. These entries obey an eight-bit unsigned integer of the form UInt8 and a 32-bit signed integer of the form Int32 following a naming convention such as C. These integer kinds have names capitalized, like all kinds in Swift. The minimum or maximum values of each integer type can also be accessed by the programmers with its minimal and max characteristics 

let minValue= UInt8.min // MinValue equal to 0,  
let maxValue= UInts8. max //maxValue equivalent to 255  

Float

This represents a 32-bit floating-point and lower decimal point number. 3.14159, 0.6 and -273.158, for instance. Swift provides two kinds of floating number points programmers.These are: 

Double

This is a floating point number of one single pixel. Programmers need to use it for high or especially accurate floating point values. 

Float used to be the float point number of a 32-bit system. Programmers do not need 64 bi accuracy when floating dot values. Double has 15 decimal numbers of accuracy, while Float's accuracy can be as few as 6 decimals. The suitable floating point type relies on the form and spectrum of values within your code that you need to operate. 

  • Bool: This data type is a Boolean value, which will be  either true or false
  • Character:This is a single character string literal. For example, "A"
  • String: This is a single unit ordered a set of characters. For example, "Hello"
  • Optional: Swift offers another data type where programmers can represent a value or no value variable.

Tuples: This data type can group multiple values in a single variable.

This is a table that shows the maximum and minimum value that can be stored in such variables:

Int81byte-127 to 127
UInt81byte0 to 255
Int324bytes-2147483648 to 2147483647
UInt324bytes0 to 4294967295
Int648bytes-9223372036854775808 to 9223372036854775807
UInt648bytes0 to 18446744073709551615
Float4bytes1.2E-38 to 3.4E+38 (~6 digits)
Double8bytes2.3E-308 to 1.7E+308 (~15 digits)

Type Aliases

You can use typealias to generate a fresh name for a current type. The easy syntax for defining a fresh type is here:

typealias newname = type

The following line, for instance, tells the compiler that distance is another Int name.

typealias Distance = Int

Now, this statement is completely legal and produces an integer variable called Feet. 

typealias Distnace= Int
var Feet:Distance= 100
print(Feet)

Type Safety

Swift is a safe type of language, meaning you can't error pass it on Int if a portion of your code expects a string. Because Swift is safe to type, type checks are carried out when you create your code and any incorrect forms are flagged as mistakes. 

var varB = 42
varB = "Hello World"
print(varB)

The above program will generate  below compile-time error: 

main.swift:2:8: error: cannot assign value of type 'String' to type 'Int' 
varB = "Hello World" 

Type Inference

This sort of inference allows a compiler to automatically deduce the sort of expression when it compiles your code merely by looking at the values. Swift utilizes inference sort in order to determine the correct type. 

// varX is inferred to be of type Int 
var varX = 60 
print(varX) 
// varY is inferred to be of type Double 
var varY = 3.14159 
print(varY) 
// varZ is also inferred to be of type Double 
var varZ = 3+0.14159 
print(varZ)

Variables

A variable gives us a storage name that can be used by our programs. A variable name cannot contain math, arrow, private use (or invalid) names, or may not start with a number even though numbers may be contained elsewhere in the same name. 

Each variable in Swift 4 has a particular type that determines the size and design of the memory of the variable, the range of values that could be stored within the memory and the set of activities that could be implemented. 

Variable declaration in Swift

A variable statement informs the compiler what type, where and how much the storage for the variable should be created. Var keywords are used to make declarations of variables. 

import Cocoa
var firstvar = 78
println(firstvar)

The output of the above program would be 78. 

Type Annotation

When declaring a variable, programmers can give an annotation type that is clear on the type of values that can be saved by the specified variable. The overall way variable is used like below : 

var variableName:<data type>=<optional initial value>

Example:

import Cocoa
var xVar = 76
println (xvar) 
var yVar:Float 
yVar = 3.14159
println (yVar)
println(" 1st Value \(varA) 2nd Value \(varB) ")

Optionals

Swift also presents an optional type that deals with the lack of value. Either "there is a value, and it is equal tox," or "there is no value" are optional. An optional one is a type alone, one of the fresh super-powered enums of Swift 4. The value, None and Some(T), are two possible values, with T being a related value of the right data type accessible in Swift. Please have a look at the below example for optional int, optional string, and optional no value: 

var optionalInt: Int?
var optionalStr: String?
var optionalStr: String? = nil

Let’s look at the below example to understand how optional works: 

var optionalString:String?=nil
if optionalString!=nil{
print(optionalString)
} else {
   print("optionalString has nil value")
}

The output of the above program would be  optionalString has nil value

Optionals are comparable to nil with Objective-C pointers, but operate on any type, not just classes. 

Forced Unwrapping

If you have optionally defined a variable, then you must unwrap the value from that variable. That only implies the mark at the end of the variable is an exclamation. Let’s try to understand this concept from the below example: 

Without forced unwrapping 

var xString:String?
 
xString = "Hello, World!"

if xString != nilprint(xString)
} else {
   print("xString has nil value")
} 

With forced unwrapping

var xString:String?

xString = "Hello, World!"

if xString != nil{
   print(xString!)/*we have used exclamation mark for forced
 unwrapping*/ 
} else print("xString has nil value")
} 

The first program output would be Optional("Hello, World!") while the second one will have "Hello, World!"

Automatic unwrapping

You can use an exclamation mark instead of a question mark to declare optional variables. These optional variables will automatically unwrap and at the end of the variable, you don't have to use another exclamation mark to get the allocated value. 

var xString:String! //We have used exclamation mark here. 
xString = "Hello, World!" 
if xString != nil{
   print(xString)//no need to use exclamation mark
} else {
   print("xString has nil value")
}

The output would be "Hello, World!"

Optional Binding

To find out whether an optional value includes a value, use the optional binding to create it, accessible as a temporary variable. Please have a look at the below syntax to understand  optional binding: 

if let constantName = someOptional { 
   statements 
} 
Example: 
var xString:String? 
xString = "Hello, World!"

if let yourString = xString { 
print("Your string has - \(yourString)") 
} else print("Your string does not have a value") 
} 

The output of the above program would be  Your string has - Hello, World! 

Tuples

Swift also presents tuples that are used in a single compound value to group various values. The values can be of any kind in a tuple and do not have to be the same.For instance ("Hello  World", 100) is a two-value multiplex, one of the type strings and another of the type integer. It's a valid syntax. 

let AuthorizedError = (401, "Not authorized") 

If a server does not execute anything on the server, it returns two values. Error code, and description. You can generate tuples from any number of values and various data types as you wish. Below is the syntax for tuple declaration: 

var TupleName = (Value1, value2,… any number of values)

Please find below valid tuple declaration:
var error401 = (401, “Not authorized”)

You can use the index numbers from 0 to access the values of tuples.  
print(“The definition of error is\(error401.1)”)

You can name tuple variables and call them by their names when you declare them.
var error401 = (errorCode: 401, description: “Not authorized”) 
print(error401.errorCode)   // prints 401. 

Tuples are useful to return multiple values from functions. Similarly, a web application could return a tuple form ("string," Int) to display whether the load was effective or not. 

By returning various values in a tuple, we can decide according to several tuple kinds. Tuples are helpful for provisional values and not suitable for complicated information. 

Constants

Constants link a name with a value of a particular type (e.g. str, pi num, or welcomeMsg).  A constant's value cannot be changed once it is set, whilst in the future, a variable may be set to a different value. This means constants in the Swift program refer to set values that will not change in the program's execution. You must declare it with the following let keyword before using constants- 

let constantName = <initial value>

This is a straightforward instance of how a constant in Swift should be declared-
let constX = 46 
print(constX) 

When the above program is executed, the output would be 46. 

Type Annotations

When you declare a constant, you can provide a type annotation to show the sort of values the constant can store. The syntax is shown below : 

var constantName:<data type> = <optional initial value>

The below example shows how to use type annotations while writing a program :
let constX = 46
print(constX) 

let constY:Float = 3.14159 
print(constY) 

We need to provide initial value while using type annotations. 

The above program output would be below : 

46 
3.1415901184082

Naming Constants

There are letters, numbers and the underscore character for a constant name. A valid constant name can start with a letter or an underscore. Upper and lowercaseletters are different because Swift is case-sensitive. 

To name your variables, you can use single or Unicode characters. Below are valid constant names: 

let _const ="Hello, World!"
print(_const)
let你好="你好世界"
print(你好)

Literals

Literal and constant values play a major role in coping with values within a program in most programming languages. The notion of literals and constants is also supported by Swift. They have a steady value and have a memory place for expressing them in the code. 

60                // Integer literal
3.14159           // Floating-point literal
"Hello, world!"   // String literal

Types of Literals in Swift

Numeric Literals

It has its subcategories as literal integer and floating-point and can be written as follows: 

  1. A decimal number, with no prefix 
  2. A binary number, with a 0b prefix 
  3. An octal number, with a 0o prefix 
  4. A hexadecimal number, with a 0x prefix 

All literals above have a decimal value of 17. It should also be noted that literals of floating points can be decimal without a prefix or a prefix of 0x hexadecimal literal. On both sides of the decimal point, they must always have a number. The optional exponent for hexadecimal floats may also contain an upper or lower case letter e and / or upper case, or lowercase letter p. 

For decimal numbers with an exponent of exp, the base number is multiplied by 10.  

For exp: 

2.25e2 means 2.25 × 102, or 225.0. 

2.25e-2 means 1.25 × 10-2, or 0.0225. 

For hexadecimal numbers with an exponent of exp, the base number is multiplied by 2exp: 

0xFp2 means 25× 22, or 100.0.
0xFp-2 means 25× 2-2, or 6.25 

String Literals 

String literal is a series of characters with a double quote beginning(") and a double quote closing(").  

"Monday" 

String literals can have a double quotation("), without escape and a backslash (\) or carry return without escape. In strings literals, unique characters must be used and another branch of strings literals called an escape sequence must be formed, with the specific significance of each escape sequence. The following are:

Escape SequenceDescription
\0Null character
\\character
\bBackspace
\fForm feed
\nNewline
\rCarriage return
\tHorizontal tab
\vVertical tab
\'Single Quote
\"Double Quote
\000Octal number of one to three digits
\xhh...Hexadecimal number of one or more digits

The following example illustrates how to use a few literals −

import Cocoa 
let str = "Hello\tWorld\n\n\'Swift\'"
println(str)

If we use the playground to operate the above program then, this outcome is  

Hello World
'Swift'

Operators

Various operators are endorsed by Swift. These symbols are used for logical and mathematical program activities. These symbols combine single constants and variables to shape phrases and execute particular tasks. In this section, you will learn about all the operators supporting Swift's coding programming language. Operators are unique symbols or sentences that are checked, combined or changed by programmers. The multiplication operator (*), for instance, multiplies two numbers. The logical AND operator & &  (as if the user name & & password) and the increased operator++iI are a complicated instance, which can help boost i's value by 1. Swift promotes most conventional C operators and removes several prevalent mistakes in coding.

There are three types of operators in swift language: 

Unary operator: These operators work on a single objective. These operators appear before the operations instantly. Two kinds of single operators are available. It is- 

Unary prefix (example:a, !value)
Unary postfix (example: x++) 

Binary operator: These operators operate with two objectives (such as 6+ 2), i.e. two operators. 

Ternary operator: These operators work on three objectives. Swift has only one ternary operator (a ? b : c). 

Types of Swift operator

1. Arithmetic Operators

OperatorsDescription
+Addition
-Subtraction
*Multiplication
/Division
%Modulus
++Increment
−−Decrement

2. Assignment Operators

OperatorsDescription
=Assign
+=Increments then assign
-+Decrements then assign
*=Multiplies then assign
/=Divides then assigns
%=Modulus then assigns

3. Comparison Operators

OperatorsDescription
==Is equal to
!=Is not equal to
>Greater than
<Less than
>=Greater than or equal to
<=Less than or equal to

4. Logical Operators

OperatorsDescription
&&And operator. Performs logical conjunction on two expressions

(if both expressions evaluate to True, the result is True. If either expression evaluates to False, the result is False)
||Or operator. Performs a logical disjunction on two expressions

(if either or both expressions evaluate to True, the result is True).
!Not operator. It performs logical negation on an expression.

5. Bitwise Operators

OperatorsDescription
&Binary AND Operator
|Binary OR Operator
^Binary XOR Operator
<<Binary Left Shift Operator
>>Binary Right Shift Operator

6. Misc Operators

This category is the conditional operator. The structure is: condition? X: Y, if a condition is true? If condition is true? Then first expression: otherwise 2nd expression. All of the above-mentioned operators are also prevalent in C and most C or C++ programmers know the operators.

7. Range Operators

OperatorsDescription
Closed RangeThis (a...b) defines  range that starts from a up to , and includes the values a and b as well example if the values in between 6 then range includes1, 2, 3, 4,5 and 6
Half-Open RangeThis (i..< j) defines i range that starts from me up to j, but does not include j. .< 6 gives 1, 2, 3, 4 and 5

Summary:

We have got a fair idea of swift keywords and basic syntax with help of this module. This module helped us in understanding the concept of Import, Tokens ,comments,.keywords ,identifiers and different operators used in Scala.

Leave a Reply

Your email address will not be published. Required fields are marked *

Comments

Rashid

I am interested in the learning of swift and coding

Arlin Burns

Is this included in csm training and certification or sold separately?

Sneha Agrawal

I am interested in advanced level training of SWIFT and coding.

Suggested Tutorials

R Programming Tutorial

R Programming

C# Tutorial

C# is an object-oriented programming developed by Microsoft that uses the .Net Framework. It utilizes the Common Language Interface (CLI) that describes the executable code as well as the runtime environment. C# can be used for various applications such as web applications, distributed applications, database applications, window applications etc.For greater understanding of this tutorial, a basic knowledge of object-oriented languages such as C++, Java etc. would be beneficial.
C# Tutorial

C# is an object-oriented programming developed by Microsoft that uses ...

Read More

Python Tutorial

Python Tutorial