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 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
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 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 */
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)
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 :
Keywords Used in Declarations | |||
Class | deinti | enum | extension |
Func | import | Init | Internal |
Let | operator | private | protocol |
public | static | struct | subscript |
typealias | var |
Keywords Used In Statements | |||
Break | Case | continue | default |
do | Else | fallthrough | for |
if | in | return | switch |
where | while |
Keywords used in expressions and types | |||
as | DynamicType | false | is |
nil | self | self | super |
true | _COLOUMN_ | _FILE_ | _FUNCTION_ |
LINE |
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 |
We have a print keyword to print anything quickly. There are three components in printing.
Let’s see an example and syntax of the same.
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 :
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
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:
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.
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:
Int8 | 1byte | -127 to 127 |
UInt8 | 1byte | 0 to 255 |
Int32 | 4bytes | -2147483648 to 2147483647 |
UInt32 | 4bytes | 0 to 4294967295 |
Int64 | 8bytes | -9223372036854775808 to 9223372036854775807 |
UInt64 | 8bytes | 0 to 18446744073709551615 |
Float | 4bytes | 1.2E-38 to 3.4E+38 (~6 digits) |
Double | 8bytes | 2.3E-308 to 1.7E+308 (~15 digits) |
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)
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"
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)
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.
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.
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) ")
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.
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:
var xString:String? xString = "Hello, World!" if xString != nil { print(xString) } else { print("xString has nil value") }
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!"
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!"
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!
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 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.
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
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(你好)
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
It has its subcategories as literal integer and floating-point and can be written as follows:
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 Sequence | Description |
---|---|
\0 | Null character |
\\ | character |
\b | Backspace |
\f | Form feed |
\n | Newline |
\r | Carriage return |
\t | Horizontal tab |
\v | Vertical tab |
\' | Single Quote |
\" | Double Quote |
\000 | Octal 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'
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).
Operators | Description |
---|---|
+ | Addition |
- | Subtraction |
* | Multiplication |
/ | Division |
% | Modulus |
++ | Increment |
−− | Decrement |
Operators | Description |
---|---|
= | Assign |
+= | Increments then assign |
-+ | Decrements then assign |
*= | Multiplies then assign |
/= | Divides then assigns |
%= | Modulus then assigns |
Operators | Description |
---|---|
== | Is equal to |
!= | Is not equal to |
> | Greater than |
< | Less than |
>= | Greater than or equal to |
<= | Less than or equal to |
Operators | Description |
---|---|
&& | 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. |
Operators | Description |
---|---|
& | Binary AND Operator |
| | Binary OR Operator |
^ | Binary XOR Operator |
<< | Binary Left Shift Operator |
>> | Binary Right Shift Operator |
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.
Operators | Description |
---|---|
Closed Range | This (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 Range | This (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.
I am interested in the learning of swift and coding
Is this included in csm training and certification or sold separately?
I am interested in advanced level training of SWIFT and coding.
C# is an object-oriented programming developed by Microsoft that uses ...
Leave a Reply
Your email address will not be published. Required fields are marked *