Swift Lect1
Swift Lect1
Swift is a new programming language developed by Apple Inc for iOS and OS X
development. Swift adopts the best of C and Objective-C, without the constraints of
C compatibility.
• Swift makes use of safe programming patterns.
• Swift provides modern programming features.
• Swift provides Objective-C like syntax.
• Swift is a fantastic way to write iOS and OS X apps.
• Swift provides seamless access to existing Cocoa frameworks.
• Swift unifies the procedural and object-oriented portions of the
language.
• Swift does not need a separate library import to support functionalities
like input/output or string handling.
Swift uses the same runtime as the existing Obj-C system on Mac OS and iOS, which
enables Swift programs to run on many existing iOS 6 and OS X 10.8 platforms.
Swift comes with playground feature where Swift 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 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.
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 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 like 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 programming environment ready and you can
proceed with your learning vehicle "Tutorials Point".
We have already seen a piece of Swift 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 −
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 program, so that it will be easy for you
to understand the basic building blocks of the Swift programming language.
Import in Swift
You can use the import statement to import any Objective-C framework (or C library)
directly into your Swift 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.
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.
Tokens in Swift
A Swift 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
statement consists of three tokens −
print("test!")
The individual tokens are:
print("test!")
Comments
Comments are like helping texts in your Swift program. They are ignored by the
compiler. Multi-line comments start with /* and terminate with the characters */ as
shown below −
/* My first program in Swift */
Multi-line comments can be nested in Swift. Following is a valid comment in Swift −
/* My first program in Swift is Hello, World!
/* Where as second program is Hello, Swift! */ */
Single-line comments are written using // at the beginning of the comment.
// My first program in Swift
Semicolons
Swift 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 −
Identifiers
A Swift 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 does not allow special characters such as @, $, and % within identifiers. Swift
is a case sensitive programming language. Thus, Manpower and manpower are two
different identifiers in Swift. 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 valid identifier, but `class` is valid.
Keywords
The following keywords are reserved in Swift. 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_
weak willSet
Whitespaces
A line containing only whitespace, possibly with a comment, is known as a blank line,
and a Swift compiler totally ignores it.
Whitespace is the term used in Swift to describe blanks, tabs, newline characters,
and comments. Whitespaces separate one part of a statement from another and
enable the compiler to identify where one element in a statement, such as int, ends
and the next element begins. Therefore, in the following statement −
var age
There must be at least one whitespace character (usually a space)
between var and age for the compiler to be able to distinguish them. On the other
hand, in the following statement −
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 readability.
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 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.
Print has three different properties.
Items – Items to be printed
Separator – separator between items
Terminator – the value with which line 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 \n" Adds, \n 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 \n , newline Feed as terminator by
default, whereas 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
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 like to store information of various data types like 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.
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 Aliases
You can create a new name for an existing type using typealias. Here is the simple syntax to
define a new type using typealias −
typealias newname = type
For example, the following line instructs the compiler that Feet is another name for Int −
typealias Feet = Int
Now, the following declaration is perfectly legal and creates an integer variable called distance
−
Type Safety
Swift 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 is type-safe, it performs type-checks when compiling 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 uses type
inference to work out the appropriate type as follows.
When we run the above program using playground, we get the following result −
42
3.14159
3.14159
A variable provides us with named storage that our programs can manipulate. Each
variable in Swift has a specific type, which determines the size and layout of the
variable's memory; the range of values that can be stored within that memory; and
the set of operations that can be applied to the variable.
Swift 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 literal. For example, "C"
Swift 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 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 −
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 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 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 你好 = "你好世界"
print(你好)
When we run the above program using playground, we get the following result.
Hello, Swift!
你好世界
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 valid examples −
When we run the above program using playground, we get the following result.
Value of Godzilla is more than 1000.0 millions
Swift 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’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.
Here’s an optional Integer declaration −
var perhapsInt: Int?
Here’s an optional String declaration −
var perhapsStr: String?
The above declaration is equivalent to explicitly initializing it to nil which means no
value −
var perhapsStr: String? = nil
Let's take the following example to understand how optionals work in Swift −
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?
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!")
Now let's apply unwrapping to get the correct value of the variable −
var myString:String?
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!
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!"
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!
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 −
var myString:String?
myString = "Hello, Swift!"
When we run the above program using playground, we get the following result −
Your string has - Hello, Swift!