Swift Basic

Chapter 1

Share on facebook
Facebook
Share on twitter
Twitter
Share on linkedin
LinkedIn

[vc_row css=”.vc_custom_1487155612209{padding-bottom: 40px !important;}”][vc_column][vc_column_text]

Swift Basic

[/vc_column_text][/vc_column][/vc_row][vc_row][vc_column][vc_tta_tour][vc_tta_section title=”Page 1″ tab_id=”1549347676769-a7eb28e4-21e9″][vc_column_text]Swift is new programming language for developing iOS and Mac OS applications. Apple at WWDC 2014 introduced Swift. Swift is not based on C and is different from the Objective C language. It takes the scripting approach making it easier for developer to understand. Apple main aim is to make Application developer life easier so that more and more solutions are uploaded on the  App’s Store. In order to achieve this goal Swift is introduced.

For any language most important to understand is how variables, constants and functions are declared and are used. We will go into these one by one before we start writing the code in the Xcode.

1. SWIFT Variable

We declare variables in Swift by using “var” keyword. Throughout this book we will be using various real world examples to make things easier to understand. We will start with simple example of making ID making App. This App will help user to design the ID card.

For making the ID card for the student we need student unique code (roll number), first name, last name, course name, age and nationality.

We will declare all these parameters as variables in the program as follows

var rollnumber

Suppose we need to initialize the variables than we will use following statement.

var rollNumber = 1

var firstName =“Priyank”

var lastName=“Ranka”

var courseName=“Programming Language”

var age=28

var nationality=“India”[/vc_column_text][/vc_tta_section][vc_tta_section title=”Page 2″ tab_id=”1549347676784-b7f69933-94b1″][vc_column_text]Following some points we can observe from above initialization.

a. Unlike other languages, Swift does not require you to write semicolon (;) after each statement in your code.

b. You can avoid writing datatype for each variable you declare. Swift will convert the variable into respective datatype when variable gets  the value for the first time.
c. You can change the value of the variable after initialization

d. One can declare and initialize multiple variables in single line as follows var x = 0.0, y = 0.0, z = 0.0

e. One has to write semicolon if you have to write multiple statements in single line.

For example var age = 28; println(age)

f. We can use any character for declaring variables even Unicode characters like smiles and other Unicode characters.

2. Type Annotation
You can declare the variables with the specific type using type annotation.
The syntax is as follows

var firstName : String

The colon in the declaration means “of type”, so we can read as “firstName is of type String”.
firstName = “Priyank” // It is valid

firstName  =  10//complier will give an error as we have declared firstName as String and thus can not assign integer value

Note: It is rare we use type annotation.[/vc_column_text][/vc_tta_section][vc_tta_section title=”Page 3″ tab_id=”1549347811729-970a92c3-a1b5″][vc_column_text]3.    Swift Constants

We declare constants in Swift by using “let” keyword. Value of a constant will never change.

let  photoWidth    =     200.0

let photoHeight     =    300.00

4.    Type Aliases

Type Aliases is similar to type def. We can use different name for the datatype by using keyword “typealias”.

typealias NimapINT = int

One can use NimapINT to represent int in the code by writing the above line of code.

5.    Tuple Data Type

The Swift introduces this data type, which is not there in Objective C. With tuples you can group multiple values. Thus tuples allows you to group different type of values into one compound value. Thus one can return tuple type of data in order to return multiple values from the method.

let idError = (100,”First Name Of Student Missing”)

We have declared tuple idError which group Int and String to give ID card error with code and human readable string. This can be described as “tuple of type (Int, String)”. You can create tuples with any permutation of type like (Int,Int,Int) or (String,Boolean) or (Int,Float,Student).

Now question comes, how can we read values from tuples? There are various ways we can decompose tuples to extract the values.

let (errorCode,errorMessage) = idError

After the above line whenever you refer “errorCode” it will referred as “100”. And whenever you refer “errorMessage” it will be referred as “First Name Of Student Missing”.[/vc_column_text][/vc_tta_section][vc_tta_section title=”Page 4″ tab_id=”1549347874622-bc943395-90de”][vc_column_text]Another way to decompose the tuple is to name the individual element in a tuple when initializing the tuple.

let idError = (errorCode : 100, errorMessage : “First Name Of Student Missing”)

If you name the element in the tuple, you can use the elements name to access those elements.

Thus you can access tuple elements as idError.errorCode  or idError.errorMessage

The most important use of the tuple is to return more information from the function rather than returning the single value.

Note: Tuple should be used when group of related data is needed for temporary scope.

6.    Optional Variable or Constant

Optional are used in situation where there can be value or value does not exist. Optional concept is not available in the C or Objective C. In Objective C we had to come extends concept of optional called as nil object, with nil meaning “absence of the valid object”. But objective C does not provide optional concept for primitive types or structure types of variables and constant.

In order to declare the optional type, you need to use “?” after data type name. Thus Int will denote integer value but Int? will denote an optional integer value. An inbuilt example is toInt method of String class. toInt method returns Int? an optional Int value. This is because it is not always toInt will return an integer value. “123” will be converted into integer 123 but “Priyank Ranka” will not be converted into integer value. Thus toInt method might fail to return valid Int value, so better to use optional Int value.

In order to access the optional value it is always better to use “if” statement to check whether optional value exist in the variable or not, “if” statement will return true if value exists else false.

We need to use exclamation mark “!” to access the optional value. Run time system will throw an error if we try to access the optional value, which does not have value. Thus you need to use “if” statement and “!” mark to access the optional value.

Accessing the optional value using “!” is known as “Forced UnWrapping”.

var   ageString    =    “25”

let age         =     ageString.toInt(“123”)

if age
{

let retirementAgeLeft = 60 – age!
}[/vc_column_text][/vc_tta_section][vc_tta_section title=”Page 5″ tab_id=”1549347898601-a88a1544-ea53″][vc_column_text]1.1.Optional Binding
Optional Binding is used in the situation when optional contains value and you need to make that value available temporary. Optional Binding is used in “if” and “while” statement when condition returns an optional and the value inside the optional need to be made available inside the condition scope.

if let optionalAge = ageString.toInt(“123”)
{
let retirementAgeLeft = 60 – optionalAge
}
So above statement you can interpret as if optional return by ageString.toInt() contains a value make it available to constant “optionalAge”. This constant will
be available within the “if “ statement scope. Note: If you see we did not use “!” to access the optional Age because optional Age already got the value using option binding We can use “nil” with any optional. Only optional can be assign to nil value, nil in objective C is pointer to non-exisiting object. In Swift, nil is not a pointer but absence of value for any type.
Var age: Int? = 30
Age = nil
var firstName: String? // default it will assign to nil[/vc_column_text][/vc_tta_section][vc_tta_section title=”Page 6″ tab_id=”1549348012957-c2bd446b-32aa”][vc_column_text]Sometimes it is clear from a program’s structure that an optional will always have a value, after that value is first set. In these cases, it is useful to remove the need to check and unwrap the optional’s value every time it is accessed, because it can be safely assumed to have a value all of the time. These kinds of optionals are defined as implicitly unwrapped optionals. You write an
implicitly unwrapped optional by placing an exclamation mark (String!) rather than a question mark (String?) after the type that you want to make optional.
let photoWidth: Float? = 200.0
let photoHeight: Float! = 300.00

ipadPhotoWidth = 2.4 * photoWidth!
ipadPhotoHeight = 2.3 * photoHeight
You can think of an implicitly unwrapped optional as giving permission for the optional to be unwrapped automatically whenever it is used. Rather than placing an exclamation mark after the optional’s name each time you use it, you place an exclamation mark after the optional’s type when you declare it.
Implicitly unwrapped optionals should not be used when there is a possibility of a variable becoming nil at a later point. Always use a normal optional type if you need to check for a nil value during the lifetime of a variable.
7. Functions or Methods
In object oriented we work around the object. An object is a capsule having the state and behaviour. State is represented as variable and behaviour is represented as method. We have already seen various ways to declare variables in Swift. Lets discuss how to declare and call the methods.
We will compare method declaration in other language and Objective C and compare it with the Swift.[/vc_column_text][/vc_tta_section][vc_tta_section title=”Page 7″ tab_id=”1549348134144-5e8d466e-0a72″][vc_column_text]In C++ or JAVA we declare and call method as follow int getRollNumber();
int a = s1.getRollNumber;
Where s1 is the object of Student and we use dot operator to call the method of the Student Object.
In Objective C it will as follows
-(int) getRollNumber;
int a = [s1 getRollNumber];
In Swift it will be as follows
func getRollNumber() —> Int
var a = s1.getRollNumber()
In Swift we use word “func” to declare the method, followed by the function/method name, followed by () and finally return type is written at extreme right with