Swift Tutorial PDF
Swift Tutorial PDF
Swift 4
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.
Audience
This tutorial is designed for software programmers who would like to learn the basics of
Swift 4 programming language from scratch. This tutorial will give you enough
understanding on Swift 4 programming language from where you can take yourself to
higher levels of expertise.
Prerequisites
Before proceeding with this tutorial, you should have a basic understanding of Computer
Programming terminologies and exposure to any programming language.
Try the following example using Try it option available at the top right corner of the
following sample code box:
import Cocoa
All the content and graphics published in this e-book are the property of Tutorials Point (I)
Pvt. Ltd. The user of this e-book is prohibited to reuse, retain, copy, distribute or republish
any contents or a part of contents of this e-book in any manner without written consent
of the publisher.
We strive to update the contents of our website and tutorials as timely and as precisely as
possible, however, the contents may contain inaccuracies or errors. Tutorials Point (I) Pvt.
Ltd. provides no guarantee regarding the accuracy, timeliness or completeness of our
website or its contents including this tutorial. If you discover any errors on our website or
in this tutorial, please notify us at contact@tutorialspoint.com.
i
Swift 4
Table of Contents
About the Tutorial .................................................................................................................................... i
Audience .................................................................................................................................................. i
Prerequisites ............................................................................................................................................ i
Comments ............................................................................................................................................... 7
Semicolons .............................................................................................................................................. 7
Identifiers................................................................................................................................................ 7
Keywords ................................................................................................................................................ 8
Whitespaces ............................................................................................................................................ 9
Literals .................................................................................................................................................... 9
Printing in Swift....................................................................................................................................... 9
ii
Swift 4
Variable Declaration.............................................................................................................................. 15
Boolean Literals..................................................................................................................................... 25
iii
Swift 4
Assignment Operators........................................................................................................................... 29
Misc Operators...................................................................................................................................... 31
if Statement .......................................................................................................................................... 34
Nested If Statements............................................................................................................................. 38
Create a String....................................................................................................................................... 53
Empty String.......................................................................................................................................... 53
iv
Swift 4
Accessing Arrays.................................................................................................................................... 62
v
Swift 4
Filtering ................................................................................................................................................. 71
vi
Swift 4
vii
Swift 4
viii
Swift 4
ix
Swift 4
Defining Model Classes for Optional Chaining & Accessing Properties ................................................ 160
Methods.............................................................................................................................................. 188
Subscripts............................................................................................................................................ 189
x
Swift 4
Access Control for Constants, variables, properties and subscripts ..................................................... 215
xi
Swift 4
1. Swift 4 – 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 compatibility.
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 public 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.
1
Swift 4
2. Swift 4 – Environment
Try the following example using the Try it option available at the top right corner of the
following sample code box:
import Cocoa
print(myString)
For most of the examples given in this tutorial, you will find a Try it option, so just make
use of it and enjoy your learning.
To start with, we consider you already have an account at Apple Developer website. Once
you are logged in, go to the following link:
2
Swift 4
Now select xCode and download it by clicking on the given link near to disc image. After
downloading the dmg file, you can install it by simply double-clicking on it and following
the given instructions. Finally, follow the given instructions and drop xCode icon into the
Application folder.
Now you have xCode installed on your machine. Next, open Xcode from the Application
folder and proceed after accepting the terms and conditions. If everything is fine, you will
get the following screen:
3
Swift 4
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
If you create the same program for OS X program, then it will include import Cocoa and
the program will look like as follows:
import Cocoa
var str = "Hello, playground"
4
Swift 4
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".
5
Swift 4
3. Swift 4 – 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:
import Cocoa
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 library)
directly into your Swift 4 program. For example, the above import cocoa statement
makes all Cocoa libraries, APIs, and runtimes that form the development layer for all of
OS X, available in Swift 4.
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 literal, or a symbol. For example, the following Swift 4 statement
consists of three tokens:
print("test!")
6
Swift 4
Comments
Comments are like helping texts in your Swift 4 program. They are ignored by the
compiler. Multi-line comments start with /* and terminate with the characters */ as shown
below:
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 line, then it is required to use
a semicolon as a delimiter, otherwise the compiler will raise a syntax error. You can write
the above Hello, World! program as follows:
import Cocoa
/* 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 user-
defined 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:
7
Swift 4
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 valid identifier, but `class` is valid.
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:
typealias var
if in return switch
where while
_LINE_
8
Swift 4
weak willSet
Whitespaces
A line containing only whitespace, possibly with a comment, is known as a blank line, and
a Swift 4 compiler totally ignores it.
Whitespace is the term used in Swift 4 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:
no whitespace characters are necessary between fruit and =, or between = and apples,
although you are free to include some for better readability.
Literals
A literal is the source code representation of a value of an integer, floating-point number,
or string type. The following are examples of literals:
92 // Integer literal
4.24159 // Floating-point literal
"Hello, World!" // String literal
Printing in Swift
To print anything in swift we have ‘ print ‘ keyword.
9
Swift 4
Terminator – the value with which line should end, let’s see a example and syntax of same.
In the above code first print statement adds \n , newline Feed as terminator by default,
where as in second print statement we’ve given “ End ” as terminator, hence it’ll print “End
” instead of \n.
We can give our custom separator and terminators according to our requirement.
10
Swift 4
11