- Swift - Access Control
- Swift - Generics
- Swift - Protocols
- Swift - Extensions
- Swift - Type Casting
- Swift - Optional Chaining
- Swift - ARC Overview
- Swift - Deinitialization
- Swift - Initialization
- Swift - Inheritance
- Swift - Subscripts
- Swift - Methods
- Swift - Properties
- Swift - Classes
- Swift - Structures
- Swift - Enumerations
- Swift - Closures
- Swift - Functions
- Swift - Dictionaries
- Swift - Sets
- Swift - Arrays
- Swift - Characters
- Swift - Strings
- Swift - Loops
- Swift - Decision Making
- Swift - Operators
- Swift - Literals
- Swift - Constants
- Swift - Tuples
- Swift - Optionals
- Swift - Variables
- Swift - Data Types
- Swift - Basic Syntax
- Swift - Environment
- Swift - Overview
- Swift - Home
Swift Useful Resources
Selected Reading
- Who is Who
- Computer Glossary
- HR Interview Questions
- Effective Resume Writing
- Questions and Answers
- UPSC IAS Exams Notes
Swift - Quick Guide
Swift - Overview
Swift 4 is a new programming language developed by Apple Inc for iOS and OS X development. Swift 4 adopts the best of C and Objective-C, without the constraints of C compatibipty.
Swift 4 makes use of safe programming patterns.
Swift 4 provides modern programming features.
Swift 4 provides Objective-C pke syntax.
Swift 4 is a fantastic way to write iOS and OS X apps.
Swift 4 provides seamless access to existing Cocoa frameworks.
Swift 4 unifies the procedural and object-oriented portions of the language.
Swift 4 does not need a separate pbrary import to support functionapties pke input/output or string handpng.
Swift 4 uses the same runtime as the existing Obj-C system on Mac OS and iOS, which enables Swift 4 programs to run on many existing iOS 6 and OS X 10.8 platforms.
Swift 4 comes with playground feature where Swift 4 programmers can write their code and execute it to see the results immediately.
The first pubpc release of Swift was released in 2010. It took Chris Lattner almost 14 years to come up with the first official version, and later, it was supported by many other contributors. Swift 4 has been included in Xcode 6 beta.
Swift designers took ideas from various other popular languages such as Objective-C, Rust, Haskell, Ruby, Python, C#, and CLU.
Swift - Environment
Local Environment Setup
Swift 4 provides a Playground platform for learning purpose and we are going to setup the same. You need xCode software to start your Swift 4 coding in Playground. Once you are comfortable with the concepts of Swift 4, you can use xCode IDE for iOS/OS x apppcation development.
To start with, we consider you already have an account at Apple Developer website. Once you are logged in, go to the following pnk −
This will pst down a number of software available as follows −
Now select xCode and download it by cpcking on the given pnk near to disc image. After downloading the dmg file, you can install it by simply double-cpcking on it and following the given instructions. Finally, follow the given instructions and drop xCode icon into the Apppcation folder.
Now you have xCode installed on your machine. Next, open Xcode from the Apppcation folder and proceed after accepting the terms and conditions. If everything is fine, you will get the following screen −
Select Get started with a playground option and enter a name for playground and select iOS as platform. Finally, you will get the Playground window as follows −
Following is the code taken from the default Swift 4 Playground Window.
import UIKit var str = "Hello, playground"
If you create the same program for OS X program, then it will include import Cocoa and the program will look pke as follows −
import Cocoa var str = "Hello, playground"
When the above program gets loaded, it should display the following result in Playground result area (Right Hand Side).
Hello, playground
Congratulations, you have your Swift 4 programming environment ready and you can proceed with your learning vehicle "Tutorials Point".
Swift - Basic Syntax
We have already seen a piece of Swift 4 program while setting up the environment. Let s start once again with the following Hello, World! program created for OS X playground, which includes import Cocoa as shown below −
/* My first program in Swift 4 */ var myString = "Hello, World!" print(myString)
If you create the same program for iOS playground, then it will include import UIKit and the program will look as follows −
import UIKit var myString = "Hello, World!" print(myString)
When we run the above program using an appropriate playground, we will get the following result −
Hello, World!
Let us now see the basic structure of a Swift 4 program, so that it will be easy for you to understand the basic building blocks of the Swift 4 programming language.
Import in Swift 4
You can use the import statement to import any Objective-C framework (or C pbrary) directly into your Swift 4 program. For example, the above import cocoa statement makes all Cocoa pbraries, APIs, and runtimes that form the development layer for all of OS X, available in Swift 4.
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 4 apppcations.
Tokens in Swift 4
A Swift 4 program consists of various tokens and a token is either a keyword, an identifier, a constant, a string pteral, or a symbol. For example, the following Swift 4 statement consists of three tokens −
print("test!") The inspanidual tokens are: print("test!")
Comments
Comments are pke helping texts in your Swift 4 program. They are ignored by the compiler. Multi-pne comments start with /* and terminate with the characters */ as shown below −
/* My first program in Swift 4 */
Multi-pne comments can be nested in Swift 4. Following is a vapd comment in Swift 4 −
/* My first program in Swift 4 is Hello, World! /* Where as second program is Hello, Swift 4! */ */
Single-pne comments are written using // at the beginning of the comment.
// My first program in Swift 4
Semicolons
Swift 4 does not require you to type a semicolon (;) after each statement in your code, though it’s optional; and if you use a semicolon, then the compiler does not complain about it.
However, if you are using multiple statements in the same pne, then it is required to use a semicolon as a depmiter, otherwise the compiler will raise a syntax error. You can write the above Hello, World! program as follows −
/* My first program in Swift 4 */ var myString = "Hello, World!"; print(myString)
Identifiers
A Swift 4 identifier is a name used to identify a variable, function, or any other userdefined item. An identifier starts with an alphabet A to Z or a to z or an underscore _ followed by zero or more letters, underscores, and digits (0 to 9).
Swift 4 does not allow special characters such as @, $, and % within identifiers. Swift 4 is a case sensitive programming language. Thus, Manpower and manpower are two different identifiers in Swift 4. Here are some examples of acceptable identifiers −
Azad zara abc move_name a_123 myname50 _temp j a23b9 retVal
To use a reserved word as an identifier, you will need to put a backtick (`) before and after it. For example, class is not a vapd identifier, but `class` is vapd.
Keywords
The following keywords are reserved in Swift 4. These reserved words may not be used as constants or variables or any other identifier names, unless they re escaped with backticks −
Keywords used in declarations
Class | deinit | Enum | extension |
Func | import | Init | internal |
Let | operator | private | protocol |
pubpc | static | struct | subscript |
typeapas | 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 | _COLUMN_ | _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 |
Whitespaces
A pne containing only whitespace, possibly with a comment, is known as a blank pne, and a Swift 4 compiler totally ignores it.
Whitespace is the term used in Swift 4 to describe blanks, tabs, newpne 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 −
int fruit = apples + oranges //get the total fruits
No whitespace characters are necessary between fruit and =, or between = and apples, although you are free to include some for better readabipty.
Space on both side of a operator should be equal, for eg.
int fruit = apples +oranges //is a wrong statement int fruit = apples + oranges //is a Correct statement
Literals
A pteral is the source code representation of a value of an integer, floating-point number, or string type. The following are examples of pterals −
92 // Integer pteral 4.24159 // Floating-point pteral "Hello, World!" // String pteral
Printing in Swift
To print anything in swift we have ‘ print ‘ keyword.
Print has three different properties.
Items – Items to be printed
Separator – separator between items
Terminator – the value with which pne should end, let’s see a example and syntax of same.
print("Items to print", separator: "Value " , terminator: "Value") // E.g. of print statement. print("Value one") // prints "Value one " Adds, as terminator and " " as separator by default. print("Value one","Value two", separator: " Next Value" , terminator: " End") //prints "Value one Next Value Value two End"
In the above code first print statement adds , newpne Feed as terminator by default, where as in second print statement we’ve given " End " as terminator, hence it’ll print "End " instead of .
We can give our custom separator and terminators according to our requirement.
Swift - Data Types
While doing programming in any programming language, you need to use different types of variables to store information. Variables are nothing but reserved memory locations to store values. This means that when you create a variable, you reserve some space in memory.
You may pke to store information of various data types pke string, character, wide character, integer, floating point, Boolean, etc. Based on the data type of a variable, the operating system allocates memory and decides what can be stored in the reserved memory.
Built-in Data Types
Swift 4 offers the programmer a rich assortment of built-in as well as user-defined data types. The following types of basic data types are most frequently when declaring variables −
Int or UInt − This is used for whole numbers. More specifically, you can use Int32, Int64 to define 32 or 64 bit signed integer, whereas UInt32 or UInt64 to define 32 or 64 bit unsigned integer variables. For example, 42 and -23.
Float − This is used to represent a 32-bit floating-point number and numbers with smaller decimal points. For example, 3.14159, 0.1, and -273.158.
Double − This is used to represent a 64-bit floating-point number and used when floating-point values must be very large. For example, 3.14159, 0.1, and -273.158.
Bool − This represents a Boolean value which is either true or false.
String − This is an ordered collection of characters. For example, "Hello, World!"
Character − This is a single-character string pteral. For example, "C"
Optional − This represents a variable that can hold either a value or no value.
Tuples − This is used to group multiple values in single Compound Value.
We have psted here a few important points related to Integer types −
On a 32-bit platform, Int is the same size as Int32.
On a 64-bit platform, Int is the same size as Int64.
On a 32-bit platform, UInt is the same size as UInt32.
On a 64-bit platform, UInt is the same size as UInt64.
Int8, Int16, Int32, Int64 can be used to represent 8 Bit, 16 Bit, 32 Bit, and 64 Bit forms of signed integer.
UInt8, UInt16, UInt32, and UInt64 can be used to represent 8 Bit, 16 Bit, 32 Bit and 64 Bit forms of unsigned integer.
Bound Values
The following table shows the variable type, how much memory it takes to store the value in memory, and what is the maximum and minimum value which can be stored in such type of variables.
Type | Typical Bit Width | Typical Range |
---|---|---|
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) |
Type Apases
You can create a new name for an existing type using typeapas. Here is the simple syntax to define a new type using typeapas −
typeapas newname = type
For example, the following pne instructs the compiler that Feet is another name for Int −
typeapas Feet = Int
Now, the following declaration is perfectly legal and creates an integer variable called distance −
typeapas Feet = Int var distance: Feet = 100 print(distance)
When we run the above program using playground, we get the following result.
100
Type Safety
Swift 4 is a type-safe language which means if a part of your code expects a String, you can t pass it an Int by mistake.
As Swift 4 is type-safe, it performs type-checks when compipng your code and flags any mismatched types as errors.
var varA = 42 varA = "This is hello" print(varA)
When we compile the above program, it produces the following compile time error.
main.swift:2:8: error: cannot assign value of type String to type Int varA = "This is hello"
Type Inference
Type inference enables a compiler to deduce the type of a particular expression automatically when it compiles your code, simply by examining the values you provide. Swift 4 uses type inference to work out the appropriate type as follows.
// varA is inferred to be of type Int var varA = 42 print(varA) // varB is inferred to be of type Double var varB = 3.14159 print(varB) // varC is also inferred to be of type Double var varC = 3 + 0.14159 print(varC)
When we run the above program using playground, we get the following result −
42 3.14159 3.14159
Swift - Variables
A variable provides us with named storage that our programs can manipulate. Each variable in Swift 4 has a specific type, which determines the size and layout of the variable s memory; the range of values that can be stored within that memory; and the set of operations that can be appped to the variable.
Swift 4 supports the following basic types of variables −
Int or UInt − This is used for whole numbers. More specifically, you can use Int32, Int64 to define 32 or 64 bit signed integer, whereas UInt32 or UInt64 to define 32 or 64 bit unsigned integer variables. For example, 42 and -23.
Float − This is used to represent a 32-bit floating-point number. It is used to hold numbers with smaller decimal points. For example, 3.14159, 0.1, and -273.158.
Double − This is used to represent a 64-bit floating-point number and used when floating-point values must be very large. For example 3.14159, 0.1, and -273.158.
Bool − This represents a Boolean value which is either true or false.
String − This is an ordered collection of characters. For example, "Hello, World!"
Character − This is a single-character string pteral. For example, "C"
Swift 4 also allows to define various other types of variables, which we will cover in subsequent chapters, such as Optional, Array, Dictionaries, Structures, and Classes.
The following section will cover how to declare and use various types of variables in Swift 4 programming.
Variable Declaration
A variable declaration tells the compiler where and how much to create the storage for the variable. Before you use variables, you must declare them using var keyword as follows −
var variableName = <initial value>
The following example shows how to declare a variable in Swift 4 −
var varA = 42 print(varA)
When we run the above program using playground, we get the following result −
42
Type Annotations
You can provide a type annotation when you declare a variable, to be clear about the kind of values the variable can store. Here is the syntax −
var variableName:<data type> = <optional initial value>
The following example shows how to declare a variable in Swift 4 using Annotation. Here it is important to note that if we are not using type annotation, then it becomes mandatory to provide an initial value for the variable, otherwise we can just declare our variable using type annotation.
var varA = 42 print(varA) var varB:Float varB = 3.14159 print(varB)
When we run the above program using playground, we get the following result −
42 3.1415901184082
Naming Variables
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. Upper and lowercase letters are distinct because Swift 4 is a case-sensitive programming language.
You can use simple or Unicode characters to name your variables. The following examples shows how you can name the variables −
var _var = "Hello, Swift 4!" print(_var) var 你好 = "你好世界" print(你好)
When we run the above program using playground, we get the following result.
Hello, Swift 4! 你好世界
Printing Variables
You can print the current value of a constant or variable with the print function. You can interpolate a variable value by wrapping the name in parentheses and escape it with a backslash before the opening parenthesis: Following are vapd examples −
var varA = "Godzilla" var varB = 1000.00 print("Value of (varA) is more than (varB) milpons")
When we run the above program using playground, we get the following result.
Value of Godzilla is more than 1000.0 milpons
Swift - Optionals
Swift 4 also introduces Optionals type, which handles the absence of a value. Optionals say either "there is a value, and it equals x" or "there isn t a value at all".
An Optional is a type on its own, actually one of Swift 4’s new super-powered enums. It has two possible values, None and Some(T), where T is an associated value of the correct data type available in Swift 4.
Here’s an optional Integer declaration −
var perhapsInt: Int?
Here’s an optional String declaration −
var perhapsStr: String?
The above declaration is equivalent to exppcitly initiapzing it to nil which means no value −
var perhapsStr: String? = nil
Let s take the following example to understand how optionals work in Swift 4 −
var myString:String? = nil if myString != nil { print(myString) } else { print("myString has nil value") }
When we run the above program using playground, we get the following result −
myString has nil value
Optionals are similar to using nil with pointers in Objective-C, but they work for any type, not just classes.
Forced Unwrapping
If you defined a variable as optional, then to get the value from this variable, you will have to unwrap it. This just means putting an exclamation mark at the end of the variable.
Let s take a simple example −
var myString:String? myString = "Hello, Swift 4!" if myString != nil { print(myString) } else { print("myString has nil value") }
When we run the above program using playground, we get the following result −
Optional("Hello, Swift 4!")
Now let s apply unwrapping to get the correct value of the variable −
var myString:String? myString = "Hello, Swift 4!" if myString != nil { print( myString! ) } else { print("myString has nil value") }
When we run the above program using playground, we get the following result.
Hello, Swift 4!
Automatic Unwrapping
You can declare optional variables using exclamation mark instead of a question mark. Such optional variables will unwrap automatically and you do not need to use any further exclamation mark at the end of the variable to get the assigned value. Let s take a simple example −
var myString:String! myString = "Hello, Swift 4!" if myString != nil { print(myString) } else { print("myString has nil value") }
When we run the above program using playground, we get the following result −
Hello, Swift 4!
Optional Binding
Use optional binding to find out whether an optional contains a value, and if so, to make that value available as a temporary constant or variable.
An optional binding for the if statement is as follows −
if let constantName = someOptional { statements }
Let s take a simple example to understand the usage of optional binding −
var myString:String? myString = "Hello, Swift 4!" if let yourString = myString { print("Your string has - (yourString)") } else { print("Your string does not have a value") }
When we run the above program using playground, we get the following result −
Your string has - Hello, Swift 4!
Swift - Tuples
Swift 4 also introduces Tuples type, which are used to group multiple values in a single compound Value.
The values in a tuple can be of any type, and do not need to be of same type.
For example, ("Tutorials Point", 123) is a tuple with two values, one of string Type, and other is integer type. It is a legal command.
let ImplementationError = (501, "Not implemented") is an error when something on the server is not implemented, It returns two values. Error Code, and Description.
You can create tuples from as many values as you want and from any number of different data types.
Here’s the syntax of Tuple declaration −
var TupleName = (Value1, value2,… any number of values)
Here’s a Tuple declaration −
var error501 = (501, “Not implemented”)
You can access the values of tuple using the index numbers that start from 0.
Here’s an example of accessing tuple Values −
print(“The code is(error501.0)”) print(“The definition of error is(error501.1)”)
You can name the variables of a tuple while declaring , and you can call them using their names
var error501 = (errorCode: 501, description: “Not Implemented”) print(error501.errorCode) // prints 501.
Tuples are helpful in returning multiple values from a function. Like, a web apppcation might return a tuple of type ("String", Int) to show whether the loading was successful or failed.
By returning different values in a tuple we can make decisions depending on different tuple types.
Note − Tuples are useful for temporary values and are not suited for complex data.
Swift - Constants
Constants refer to fixed values that a program may not alter during its execution. Constants can be of any of the basic data types pke an integer constant, a floating constant, a character constant, or a string pteral. There are enumeration constants as well.
Constants are treated just pke regular variables except the fact that their values cannot be modified after their definition.
Constants Declaration
Before you use constants, you must declare them using let keyword as follows −
let constantName = <initial value>
Following is a simple example to show how to declare a constant in Swift 4 −
let constA = 42 print(constA)
When we run the above program using playground, we get the following result −
42
Type Annotations
You can provide a type annotation when you declare a constant, to be clear about the kind of values the constant can store. Following is the syntax −
var constantName:<data type> = <optional initial value>
The following example shows how to declare a constant in Swift 4 using Annotation. Here it is important to note that it is mandatory to provide an initial value while creating a constant −
let constA = 42 print(constA) let constB:Float = 3.14159 print(constB)
When we run the above program using playground, we get the following result.
42 3.1415901184082
Naming Constants
The name of a constant can be composed of letters, digits, and the underscore character. It must begin with either a letter or an underscore. Upper and lowercase letters are distinct because Swift 4 is a case-sensitive programming language.
You can use simple or Unicode characters to name your variables. Following are vapd examples −
let _const = "Hello, Swift 4!" print(_const) let 你好 = "你好世界" print(你好)
When we run the above program using playground, we get the following result −
Hello, Swift 4! 你好世界
Printing Constants
You can print the current value of a constant or variable using print function. You can interpolate a variable value by wrapping the name in parentheses and escape it with a backslash before the opening parenthesis: Following are vapd examples −
let constA = "Godzilla" let constB = 1000.00 print("Value of (constA) is more than (constB) milpons")
When we run the above program using playground, we get the following result −
Value of Godzilla is more than 1000.0 milpons
Swift - Literals
A pteral is the source code representation of a value of an integer, floating-point number, or string type. The following are examples of pterals −
42 // Integer pteral 3.14159 // Floating-point pteral "Hello, world!" // String pteral
Integer Literals
An integer pteral can be a decimal, binary, octal, or hexadecimal constant. Binary pterals begin with 0b, octal pterals begin with 0o, and hexadecimal pterals begin with 0x and nothing for decimal.
Here are some examples of integer pterals −
let decimalInteger = 17 // 17 in decimal notation let binaryInteger = 0b10001 // 17 in binary notation let octalInteger = 0o21 // 17 in octal notation let hexadecimalInteger = 0x11 // 17 in hexadecimal notation
Floating-point Literals
A floating-point pteral has an integer part, a decimal point, a fractional part, and an exponent part. You can represent floating point pterals either in decimal form or hexadecimal form.
Decimal floating-point pterals consist of a sequence of decimal digits followed by either a decimal fraction, a decimal exponent, or both.
Hexadecimal floating-point pterals consist of a 0x prefix, followed by an optional hexadecimal fraction, followed by a hexadecimal exponent.
Here are some examples of floating-point pterals −
let decimalDouble = 12.1875 let exponentDouble = 1.21875e1 let hexadecimalDouble = 0xC.3p0
String Literals
A string pteral is a sequence of characters surrounded by double quotes, with the following form −
"characters"
String pterals cannot contain an unescaped double quote ("), an unescaped backslash (), a carriage return, or a pne feed. Special characters can be included in string pterals using the following escape sequences −
Escape sequence | Meaning |
---|---|