In this post, we will start with conditional statements.
In conditional statements, the execution of a statement depends upon the condition.
Swift provides if–else and switch as conditional statements.
For now, we will concern ourselves to if-else statements.
The following block of code specifies how the if-else statements are written in swift.
if ( condition ){
//execute block1
} else {
//execute this block2
}
If the condition is true, block1 executes else block2 executes.
This will be more clear once we look into some examples.
If Statement
Example: We have a variable marksOfStudents. If the marks are less than 30, we will print fail. The code will be like this
var marksOfStudents = 25
if ( marksOfStudents <= 30 ){
print("Student Fails")
}
Here we check in the condition whether marks are less than and equal to 30. Since the condition is true “Student Fails” gets printed.
Suppose the condition is false. marksOfStudent = 45 (> 30). Let’s see what happens
var marksOfStudents = 45
if ( marksOfStudents <= 30 ){
print("Student Fails")
}
There is no output. Because we have not coded the false condition.
Else Statement
To code the false condition, else is used. The code will now become:
var marksOfStudents = 45
if ( marksOfStudents <= 30 ){
print("Student Fails")
} else {
print("Student Passes")
}
We can see from the output, “Student Passes” is printed as condition is false.
Else-If Statement
Suppose we want to print division and fail base upon the marks. If marks are greater than 75, we want to award “First Division”. If marks are greater than 30 but less than 75, we want to award “Second Division”, If marks are less than 30, we want to declare “Student fails”
We can see there are multiple conditions here, which cannot be handled using only if-else. So here, we will use if-else-if. The else-if statement is used to handle additional conditions.
Let’s see how the code for this one would look like:
var marksOfStudents = 45
if ( marksOfStudents >= 75 ){
print("First Division")
} else if (marksOfStudents >30 && marksOfStudents < 75) {
print("Second Division")
} else {
print("Student fails")
}
As we can see from the code, first we check the condition whether marks are greater than or equal to 75 using if. Next we check the middle condition whether marks are between 30 and 75 using the else if. Finally we use else to handle the situation when both the conditions become false.
The output is second division. Here the else-if condition becomes true as 45 is less than 75 and greater than 30.
A set is just like an array. Only the difference being that sets have distinct values and no ordering.
example: A set of first four letters of an alphabet. [“a”, “b”, “c”, “d”]
How do we initialize a set in Swift?
We do the initialization using initializer syntax:
Let’s initialize a set containing ages of our friends.
var age = Set<Int>()
var age followed by Set, Int in open brackets, ending with function brackets.
When we print age, we see that it’s empty.
So, we need to add in the ages using
age = [38, 65, 97]
Now when we print age, we see it has three numbers 38, 65, 97.
The second method of initialization is using array literal.
For this one, we will use an array of colors.
var color : Set<String> = ["Red", "Green", "Yellow"]
The variable color is declared as a set if string values are written using Set<String>. The variable color can only save String values as we specified the type as String. Since we used three colors to initialize the set, color set is not empty.
In arrays, we used [String], but here we use Set<String> as Set type can not be inferred only with String in double brackets, word Set is very important.
This initialization can be done using only “Set” as Swift can infer the type of elements of the set because of its type inference property.
First commenting this initialization, we write
var color : Set = ["Red", "Green", "Yellow"]
Next, we work upon the “Operations on Set”
The first operation is “Inserting an element into the set“. For this, we will insert color “Blue” in the set “color”.
color.insert("Blue")
We can see here in the result bar that “Blue” has been added to set “color”
To confirm, we can print color.
A difference from the array can be seen here, we have not specified the location where we want the blue to be placed. Because unlike arrays, sets are unordered lists. So blue is added at a random position.
The subsequent function is “Removing an element from the set“. For this, we will remove color “Green” from the set.
color.remove("Green")
When we print the set now, the result is devoid of “Green”.
Now we move on to “Contain function: to check whether an element is inside the set”. Again for this first, we will check whether alphabet “a” is inside set and then check whether “Red” is inside the set.
print(color.contains("a"))
We can see the result here in the result are is “false” as “a” is not inside set color.
print(color.contains("Red"))
Red is inside set the color and so the result is true.
Next is the method to count the number of elements in the set.
print(color.count)
Clearly, the answer is 3 as seen here.
Apart from all these operations, there are certain operations that are performed on sets as we have studied in maths.
Let’s see one by one all the operations:
Consider two sets :
A = { “a”, “e”, “i”, “o”, “u” }
B = { “l”, “a”, “u”, “r”, “e”, “n” }
The two circles here denote sets A and B.
Since { “a”, “e”, “u”} is common in two sets, we place them in the intersecting of two circles.
{ “a”, “e”, “u”} is also the result of intersection of sets A and B. The yellow color is used to highlight An intersection B
Union operation on the sets leads to a set of all elements from A and B.
So here union of set A and B will have {“a”, “e”, “i”, “o”, “u”, “l”, “r”, “n”} with { “a”, “e”, “u”} only once. As we have seen earlier sets cannot have repeated values, hence no repeated values here.
On this slide, the yellow color is used to show the union of sets A and B.
Symmetric Difference gives values in each set but not in both. Here they will be { “o”, “i”, “l”, “r”, “n”}
Subtracting B from A will give values in A which are not in B. ie { “o”, “i” }
Now we will perform all these operations in Swift.
We have taken two sets:
var vowels : Set = ["a", "e", "i", "o", "u"]
var nameLetters : Set = ["l", "a", "u", "r", "e", "n"]
The first operation is Intersection
print(nameLetters.intersection(vowels))
The result is { “a”, “e”, “u”} as expected
Next is Union
print(nameLetters.union(vowels))
The result is all letters in both sets : [“a”, “i”, “r”, “n”, “u”, “e”, “l”, “o”]
For Symmetric Difference
print(nameLetters.symmetricDifference(vowels))
we get [“o”, “l”, “r”, “i”, “n”] as expected
The last is subtraction
print(nameLetters.subtracting(vowels))
The result is [“l”, “r”, “n”] as expected.
With this we complete Sets. In next post, we will cover Dictionaries, the last of collections.
Append, Insert, Remove, Count, and Retrieve are the operations that can be performed on arrays.
Append is used to add items at the end of an array. Here we are adding “Ravenclaw” to the array “house”. Ravenclaw is added to the end of the array.
Insert is used to add items at a desired position in the array.
“insert(newElement: Element, at: Int)
Here newElement is the element we want to add in the array. And after at: we specify the index at which element will be added.
In our example, we are adding “Slytherin” and index 1. Array index start from 0, so Slytherin gets added after Gryffindor which is at 0. Rest elements are shifted one place down.
Remove is used to delete items in the array.
“remove(at: Int)”
Here we just need to specify the index of the element we want to delete.
In our example we are deleting “Slytherin” which is at 1.
Count returns the total number of items in the array.
We can retrieve any element of the array through its index. Here we want to access Ravenclaw. So we use the index of Ravenclaw.
Have you guys read “Dark Places” by Gillian Flynn? I recently finished it. It is a pretty awesome murder mystery. It is a story of a girl who loses her family at a very young age in a horrible episode. When she grows up, she ventures on a journey to find out what exactly transpired that day. Do give it a read. You can find its review here.
Enough about the book. In this post, we will be learning about ‘Optionals Data Type’.
This data type is exclusive to swift. You wouldn’t find it in any other programming language such as java or python.
In our previous post, we deliberated on Type Safety property of Swift. Go ahead and visit it.
Not just with types, Swift is otherwise also a very safe language.
In case of java, null values can be assigned to variables and constants. That is not allowed in Swift.
Why not assign a nil value to a swift variable and see for ourselves?
//variable to store your favourite color
var favColor : String = nil
The compiler immediately throws an error “Nil cannot initialize specified type “String” as we expected.
Another example:
//constant to store your age
let age : Int = nil
Similar error for this one too!
It can also be seen that compiler is suggesting a fix add “?” around type “Int” / “String” to make them optional.
Swift has given this feature so that you can have a variable or constant which if not initialized can contain a “nil” value.
What are we waiting for? Let’s remove this error from both our variable and constant by making them optional types.
var favColor : String? = nil
let age : Int? = nil
We can clearly see, error vanishes like magic.
Now we are going to assign a value to our variable:
var favColor : String? = "Red"
It will work without any more impediments.
Hmm.. But we must check if we can assign an integer value to this string optional. Shouldn’t we?
var favColor : String? = 78
Uh-oh! Compiler has thrown and error “Cannot convert value of type ‘Int’ to specified type ‘String”
It means we can only assign ‘nil’ or string value to this optional variable.
So far we discussed two major items :
Optionals are declared using a “?”
They can store either “nil” value or a value of that particular type
Okay, Let’s try and use this optional variable.
print(favColor)
It is being printed. But we can see, it has got itself wrapped inside Optional() keyword.
We wouldn’t want that while using it somewhere else. Right?
So how do we unwrap an optional value?
We do it by placing “!” after the variable while using it like this:
print(favColor!)
We can see now only “Red” is printed.
Optional Binding
It can be used to find out whether an optional variable contains a value or nil.
var favColor : String? = "Red"
if let color = favColor{
print(color)
}else{
print("No color")
}
Here we declare an optional favColor and assign a value to it. Then use if let….else to test whether optional has value.
If let first checks whether the optional has a value. If it has no value, else statement is executed. If it has value then that value is implicitly unwrapped and assigned to the constant color, and following statements are executed. This is called Optional Binding.
We will learn more on the if-else and other control flow statements in our next post. Till then practice optionals and leave your questions and thoughts in comments.
PS : You can find the source code of this post here.
All iOS applications are written using Swift Language. So in following post series starting from this one, we would learn more on swift basics.
In the last post on Installing Xcode, we installed Xcode 8 on our mac.
Xcode has a playground where we can learn swift language quickly and easily. Before starting on Swift, we need to get acquainted with Playground
Therefore, we will go through the following topics step by step :
Meet Playground
Comments
Constants
Variable
Meet Playground
In this section we will see how to create a playground file and get to look at playground UI minutely.
Creating a Playground File
Open Xcode and Click on “Get Started with a playground”
Next enter a filename of your choice and click on “next”
Next choose the location where you would like to save the file and click on “create” and “finish” on the subsequent screen.
Your playground file is created and would open like this with some default text.
What’s what in Playground?
Navigation Window : This window opens when you click on the first button in the panel shown by arrow. This shows all the files in your playground.
Source Code : Here we write in our swift code.
Result Sidebar : Playground automatically runs and shows the results here. Automatic execution here means, you type in code and you see the results here.
Execution Window : This window opens when we click on the second button in the panel shown by arrow. It has a run button (blue triangle). When clicked, displays the result of swift code. It is used for manual execution.
File and Library Inspector : This window opens when we click on the third button in the panel shown by arrow.File inspector shows the details about the file and library inspector is used to add components from code library to the source code.
Comments are the lines of code which are ignored at the time of execution of code. In swift single line comments are written using “//” and multi-line comments are written within “/* ….. */”
For Example :
//Variable and Constants. This is a single line comment
/* This is a multi-line comment. You can have more than one line. */
Constants
Constants are those values which cannot change during execution.
For Example :
let firstName : String = "John"
Here firstName is the name of the constant.
String is the type of firstName and
“John” is the value assigned to firstName.
This whole line is called an expression
Let’s try to change the value of firstName
firstName = "Dave"
Playground throws an error like this :
Variables
Variables are those values which can be changed during execution. There will be no error shown.