Swift

Tuples are similar to collection datatypes like array and dictionaries. Tuples can contain values of any data type. Then, the difference between collection and tuple is, we can not add or delete an element from a tuple.

Do you wanna know the syntax and how it should be declared. Generally, Tuples are defined as a comma separated values, within a pair of parentheses.example:let nameAndAge = (“Tom Tom “, 41)
The (“Tom Tom”,41) tuple groups together a String and an Int to give the name and age of a person.
It can be described as “a tuple of type (String, Int)”.
You can create tuples from any permutation of data types, and they can contain many different data types as you like. There’s nothing stopping you from having a tuple of type (Int, Int, Int), or (String, Bool), or indeed any other permutation you require.

When to Use a Tuple:

Tuples are particularly useful as the return value of a function. A function that tries to retrieve a web page might return the (Int, String) tuple type to describe the success or failure of the page retrieval. By returning a tuple with two distinct values, each of a different type, the function provides more useful information about its outcome than if it could only return a single value of a single type.

Decomposing and accessing values from a Tuple:

We can decompose a tuple’s contents into separate constants or variables, later we then access it as usual:let (name,age) = nameAndAge // to know more about let , please visit variables in swift3 println(“Age is \(age)”)
// prints “Age is 41”println(“Name is \(name)”)
// prints “Name is Tom Tom”
Access the individual element values in a tuple using index numbers starting at zero:println(“Name is \(nameAndAge .0)”)
// prints “Name is Tom Tom”println(“Age is \(nameAndAge .1)”)
// prints “Age is 41”

Alternatively, We can name the individual elements in a tuple when the tuple is defined like below,

let nameAndAge = (name : “Tom Tom”,age:41)
If we name the elements in a tuple, we can use the element names to access the values of those elements,println(“Name is \(nameAndAge.name)”)
// prints “Name is Tom Tom”println(“Age is \(nameAndAge.age)”)
// prints “Age is 41”

Note: If we need only some of the tuple’s values, then we can ignore parts of the tuple with an underscore (_) when we decompose the tuple:
let (name, _) = nameAndAge

As we all know operators are the basic and fundamental concepts in any programming languages. In Swift, operators are same as other programming language operators, but Swift operators are more efficient and simplified than other languages which help developers using it efficiently. let’s go through operators, then on the go lets see the swift specific operators. Is it boring? if so, please bear with me.

For what we need operators and what is the purpose of it?. Simple, manipulating the values and checking the multiple variables and decide the flow of the code using decision-making syntax.

Operators are Unary, binary and ternary.

Unary Operator:

Unary operators work on a variable. Explaining by words will rotate our brain in 360 degrees. right.. let’s see an example for unary operators
lets say boolean variable ‘a’ is there, and we want to change the state of it, like true to false or vice versa.
a = !a
So here, ‘!’ is an unary operator, which operands on a variable named ‘a’.
Similarly,
a = -a
where, ‘-‘ operator changes it to a negative value if it is positive.

Hope that at this moment you could get the idea of binary operator

Binary Operator:

Nothing to explain in detail, as unary operator works on a single variable, a binary operator has two operands, wanna put one technical word, that’s why operands. So binary works on two variables like belowAddition -> a = a + bSubtraction -> a = a - bMultiplication -> a = a * bDivision -> a = a / bModulo -> a = a % b
Hope that, you can easily point the binary operators on the sample above, yes +,-,/,*% are the binary operators.

Ternary Operators:

Now hope that I need not explain about ternary operators, if I say again, like if an operator works on three operands then it is a ternary operator. You will throw a stone on me. But the sad part I have to say the same. please pick the small one. let’s see an example for that.

‘? :’ is a ternary operator, let’s take an example, we need to check the boolean, we need to print as true if it is true, or false if it is false.
how we will do generally using if condition.Bool b = falseif b == true { print("yes, it is true") } else{ print("no,it is false") }
We have written six lines for that, how it would be if we use ternary operator and write the above case in a line. Simply superb right!!(b == false) ? print(“yes,it is false”) : print(“no,it is false”)

Assignment Operator:

The assignment operator is to initialize or update the value of a variable.
below is an example for that let b = 10
As I said in the beginning of this tutorial, I am pointing the difference of assignment operator between C, objective C, and Swift.

in objective C
if a = b {
} // is valid, since it will return a value after assigning the value of b to a, but in Swift, the same condition is not valid since assignment operator in Swift never returns a value.

Before learning optional , it would have been better, if we have gone through Variables in Swift before.

Wrapping , UnWrapping in Swift

Optional values are the fundamental concept in Swift language, if a variable ends with ‘?’ in declaration, then it is an optional value(wrapping). Meaning of that it may or may not contain value for that. Bit confusing? lets see an example

let normalString : String = “variable without optional”

We have declared a constant string variable without optional ‘?’ , while printing below

print(normalString)

it writes as “variable without optional“, now let’s see what happens if we use optional ‘?’

let optionalString : String? = “String variable with optional”

print(optionalString)

It prints as “Optional(“String variable with optional”). Hope that you can see the difference. Yes, Optional ‘?’ wraps the actual value, and if we need actual value of that variable, we need to unwrap it using ‘!’ ,

print(optionalString!)

Now it prints as “String variable with optional”. I hope that now you got idea wrapping and unwrapping.

Force unwrapping:

Force unwrapping is nothing but an extracting the values from an optional ‘?’ variable . Ok, we aware that force unwrapping using exclamation mark ‘!’ will return a value. But how it will behave if it does not contain a value. Yes, it will make the application crash at run time. let’s see an example for that

fatal error: unexpectedly found nil while unwrapping an Optional value

Now we all got idea about wrapping(‘?’) , unwrapping(‘!’) and now you will have a question, What is the purpose of it? and where can we use it efficiently?. That’s where optional chaining and optional binding comes.

Optional Chaining and Optional Binding:

let’s assume that we don’t have an optional feature in Swift, and I am creating an instance as ‘a’ for the class named ‘A’ like below. But I am not initializing it properly, just declaring it.

class A{

let p : String= "property in class A"

}

let a : A

and I am accessing the property called ‘p’ which is there in that class ‘A’

Optional helps us to avoid this error and is playing a key role here. It avoids the app crashing at runtime though we forget to initialize the class object instance. Let’s take the same example again but with optional

class A{

let p : String= "property in class A"

}

var a : A?

I am accessing the property called ‘p’ which is there in that class ‘A’

print(a?.p)

Now the app won’t crash, but it will print as ‘nil’. This feature in Swift is optional chaining. in the same case, if we do force wrapping it print(a!.p)without initialize then the app will crash.

We now have basic knowledge on optional chaining, wrapping, force unwrapping then what is that optional Binding?.

Optional Binding:

Optional Binding is to get the value from an optional variable to normal variable. let’s take a look at this example

String is the special data type in programming languages, the sequence of characters is String. In Swift string variables are declared using String syntax.

And character is an element in String which is an another data type in a programming language. In swift, character syntax is Character. Ok, don’t worry I won’t leave you without telling an example for that.You will get an example in the String mutability section.

Mutable, Immutable String:

String mutability is, how we can alter the string variable. if a string is declared with var keyword if you want to get to know about var and let, please check our variable and constants tutorial. Let’s come back to our point. If a string variable is declared with var keyword, then it is a mutable string which means we can change the value of that variable at any time like we have NSMutableString in Objective C. In Swift it is very simple right.

just declare as

var mutableString : String = “Mutable string as a keyword is var”

whereas if a string is declared with let keyword string, then it is constant and we can not change the value of that string object.

let immutableString: String = “String can not be modified”

This is just similar to NSString in Objective C.

if we try to change the value of the string, the compiler will throw an error.

print(\(concatString)) // prints as string1string2 as + concatenates both strings.

Is Swift String Unicode compliant?

Unicode is an International standard format, if a text file is not supporting that then it will not be recognized by other programming languages. It clears that Unicode is for reading, encoding text from different writing systems. Swift is also Unicode compliant.

How does this Unicode work? Unicode has some background strategy that each character will have a scalar value that is Unicode scalar. For example, U+0061 is for ‘a’.

Modifying the String:

Swift provides a couple of options to access or modify the strings. It could be either through methods or subscript.

First of all, we need to initialize the string,

let myFirstString = “”

let myString = String()

In both ways we can initiate the string, both are equal and has an empty string.

Empty String:

Swift provides a method to check if the string is empty or not. Below is an example for that

ifmyString.isEmpty {

print(“String is Empty”)

}

isEmpty() method is used to check the empty string.

String Indices:

As we all know, the index is for pointing the position. Since string in a collection of characters, String has a property called index. An index gives the position of that character.

Three key points , we should keep in mind are startIndex , endIndex, offSetBy. Let me explain one by one .

startIndex gives you the first character position of the String, for example

let myString = “abcde”

ifmyString.isEmpty {

print(“String is Empty”)

}

print(“\(myString[myString.startIndex])”) // prints a

As String is a collection of characters , we are getting the first index using startIndex and accessing the first character from the String.

endIndex gives you the last character position of the String, for example

let myString = "abcde"

ifmyString.isEmpty {

print("String is Empty")

}

print("\(myString[myString.endIndex])") // prints e

As String is a collection of characters, we are getting the last index using endIndex and accessing the last character from the String.

Note: please keep in mind that we can not access a character in String using integers

Thats why our next key word offSetBy comes here, which advances the index position from startIndex in the below example

I am starting this Collection Type tutorial in the assumption that you have knowledge on Datatypes like int, string. If you want to refresh, please go through our Datatypes and String tutorial.

Lets come back to Swift Collection, it is used to store multiple values of the same type in a type. There are three types of collection in Swift 3.

Arrays

Set

Dictionary

Arrays elements are ordered collection type, whereas Set and Dictionary are unordered collection ttypes,elements in Set and Dictionary are not ordered.

Another difference between Array and Set is, Array can have duplicated elements , but values are unique in Set.

Arrays:

As we said earlier, an array is an ordered collection type, and it can have same values in multiple index i.e duplicated values.

and declaration is Array<Element>, where Element is a type of the value that array is holding. We will see an example in next section.

Array Initialisation:

If you are from String tutorial in our last chapter, this will be easier for you to understand all the initialisation in Swift.

let myFirstArray : Array<Int> = [1,2,3,4]

in shorthand , we can initialize an array as

let myFirstArray = [1,2,3,4]

Those two examples are constant arrays and we can not modify it since its keyword is declared as let.

Below is an example of creating an empty array and followed by its shorthand.

var mutableFirstArr = [Int]()

var mutableFirstArr = [] // shorthand empty array

Since it is declared with var, it is mutable and we can modify this array values at any time.

Accessing Arrays:

Accessing array is nothing but a getting the number of element from that array, get the value from particular index, modify the value at particular index, add or remove a value to/from an array

Let’s start with count, let’s take our previous example back here

let myFirstArray = [1,2,3,4]

The number of elements that array stored can be read by count method.

print(myFirstArray.count) , it prints as 4, since it has 4 values such as 1,2,3,4

Empty Array:

To determine the empty state of an array, we can use count method again, if it is zero, then the array is not having any values.

Another simple method is there in Swift, isEmpty, to check the empty array. Here no need to check the count is equal to 0 or not, pretty simple right?.

ifmyFirstArray.isEmpty{

print("array is empty")

}

else {

print("array is not empty")

}

Add & Delete :

Another key factor in a programming language is to add an element of an array. append() in Swift help us to add a new value to an existing array at the end. Let’s take the same array but with var keyword, since we are going to change it by adding a value.

var mutableFirstArr = [1,2,3,4]

mutableFirstArr.append(5)

Here I am appending number 5 at end of the array.

Alternatively, we can join two compatible type arrays using + operator easily.

mutableFirstArr += [6]

in the above line, I am adding an array that has single int element as 6 to an existing array.

We have knowledge now to add a value at the end, so next is to add value at the particular index.

mutableFirstArr.insert(0, at: 0)

The above example explains the insert method and takes an argument with at label that is the index position to insert the value in that array. Ok, Next thought in your mind would be deleting a value from an array. Am I right?

mutableFirstArr.remove(at: 5)

remove method that takes index position to delete the value from that position.

another short form to delete the last element of an array is removeLast().

Accessing array using Subscript:

To read or change a value from a particular position of an array, subscript syntax can be used. It is very simple to use.

mutableFirstArr[5] = 6

The above example replaces the value that is at the 5th position to a new value as 6.

Below is playground screenshot to brief our array tutorial.

Array iteration:

An array can be iterated using for-in loops that we will see in future.

for i inmutableFirstArr{

print(i)

}

Set:

Set in swift is more or less similar to an array. But the main difference between an array and a set is, duplicated values are not allowed in Set. And Set also performs set operations like join, intersection, union, symmetric difference.

The types that are going to be stored in Set must be hashable, in order to compute its unique value internally. If a type is not hashable, it can not be stored in Set.

Set Initialisation:

Set initialization is similar to Array, here also we have different types of initialization.

let myFirstSet : Set<Int> = [1,2,3]

let mySet = [1,2,3]

var firstSet = Set<Int>()

Since we have explained this initialisation in Array section, assume that need not to explain again. “I am bit lazy 🙂 “

Accessing and Modifying a Set:

Set can be accessed using its methods and properties.

count property is to find out the number of items or elements in a set

print(myFirstSet.count)

Just like array, Empty set can be found using isEmpty property

ifmyFirstSet.isEmpty

{

print("set is empty")

}

else {

print("set is not empty")

}

Add or remove an item:

Insert method is useful for inserting an item in an existing set, It is similar to an array, but the difference here in insert method of a set is, it won’t ask you the index position to where it needs to be placed. Can you guess that why it is like that? yep, Set is an unordered collection type, and it places the item at any place.

var firstSet = Set<Int>()

firstSet.insert(1)

And to delete an item is also same,

firstSet.remove(1)

Set iteration:

Set also can be traversed through using for-in loops.

for i infirstSet{

print(i)

}

Playground screenshot for giving a brief about Set.

I will write detail tutorial for dictionaries in next chapter. Please share this tutorial if you feel that I have given at least some basic knowledge, across your friends in social media and put your words in comment section to improve my skills

Dictionary is an another container/collection type in Swift.This tutorial gives the basic understanding of Dictionary or key value type. Dictionary and Set both collection types are unordered types whereas Array is an ordered type, items in an array are in an order. Like String or Array, Dictionary tutorial also briefs initialization, declaration, accessing and modifying the dictionary.

“Dictionary is a key value pair data type, each value in a dictionary is associated with a unique value”. This key helps to access the value from the dictionary. And the items or elements in a dictionary can be in any order.

Dictionary Initialization:

Just like other types in Swift, Dictionary also has inferred and explicit declaration.

Below example does not specify its key, value type explicitly. Hence this type of declaration is inferred.

let inferredDict = ["gender" : "male" , "name" : "ProgramTeach"]

The above declaration initializes the dictionary with two items. As both values in the dictionary are a String type, the compiler is not prompting the error to specify the type. let’s add age with Integer type value in the sample.

if you see the colored casting is to let the compiler know the type is dictionary having generic values. The below declaration is equal to that where we are explicitly specifying the Generic type in front.

Dictionary Mutability:

Mutability is same as we have NSMutableDictionary and NSDictionary in Objective C. If a dictionary declared with let keyword, it is constant and its values can not be modified. The above samples are declared with let keyword. If a dictionary is declared with var keyword, it is mutable and value of that dictionary can be modified, new key value can also be inserted.

Classes and Structures in programming language are two important concepts. Both are useful for building the block of codes and both can have properties and methods. Unlike other programming languages, Swift does not require you to create a separate interface and implementation file. Both interface and implementation can be in a single swift file.

Class and structure have some unique features.

Properties to store values.

Methods to provide functionality

Both can be extended to extend the functionality

Subscripts to access the values

Conform to protocols to provide standard functionality

Initialisers are to set up their initial values

Ok, let’s see what are the significant differences between Structure and class.

Classes have the inheritance properties which make one class can inherit the characteristics from other class. Whereas structure does not have inheritance.

Classes are the reference type, whereas structures are the value type.

Classes have the de-initializer which helps to free up the memory.

Typecasting can be done in classes that will help to identify the class type at runtime.

Example:

struct Rectangle {

var x = 0

var y = 0

var width = 100

var height = 100

}

class Rectangle {

var x = 0

var y = 0

var width = 100

var height = 100

}

Class and Structure Instances:

Initialization is the first step to prepare class, structure, and enumeration for use. Initial values can be set during object initialization. Unlike structures and Enumeration classes have de-initializer along with initializer to free up the memory.

let rectangle = Rectangle() // is the initialization for the structure and class

Structures can set the default value while creating an instance for that structure. it can be called as memberwise Initializers

Identity Operators:

We have a dedicated tutorial for swift operators . But explaining about Identity operators here should be the best. As classes are reference types, properties of different instances of a class may have the same reference in backside. So identity operator helps to check if two or more variables or constants linked to the same reference of a class or not.

=== (three equals) is to check identical and !== is to check not identical

See you on next tutorial, please do sharing and motivate us to write more efficiently.

Methods are functions which do functionality and task. Classes, Structures, and Enumeration can all have methods or functions in Swift. We all aware of that Structures and Enumerations in Objective C cannot define methods. Swift has a nice ability to define functions in Structure and Enumeration Type.

Two types methods are there in Swift just like other programming languages.

Instance Method

Type Method or Class Method

Instance Methods:

Instance methods can be accessed through the object or instance of a particular class, structure or enumeration which means it belongs to the particular class, structure or enumeration type. An instance method can access properties and other instance methods of the same type. Instance method should be declared within the scope of its type. (between { and } of the class, structure or enumeration).

‘CalculateArea’ is an instance method which calculates the area of a rectangle. This method is accessed by an instance of a class.

Type Methods:

Swift has another type of method called Type Methods that can be accessed by using the type, not by the instance of the type. ‘static’ keyword in Swift is used to define Type Methods. Classes can also use ‘class’ keyword to allow its subclasses to override this method. Both instance method and type method use dot(.) syntax to access. But the major difference is instance methods are accessible by self or by the instance of that type whereas Type methods are accessible by Type itself. To simplify our explanation below is the same sample code we have come across while studying instance method. Now we are just adding an extra method as classMethod with the static keyword.

class Rectangle {

let x = 0

let y = 0

let width = 100

let height = 100

func calculateArea() -> Int {

returnwidth * height

}

staticfunc classMethod() { //Type Method

print(“i am a type or Class method”)

}

}

let rectangle = Rectangle()

print(“The area of a rectangle is \(rectangle.calculateArea)”) // accessing instance method