Chapter 2

Abhinav Gupta
5 min readApr 24, 2021

--

Welcome to the next step in the process of building your very own iOS app. Firstly I would like to acknowledge “Beginning iOS Programming with Swift via @appcodamobile https://www.appcoda.com/swift/” for providing me the source material for learning Swift and Xcode myself so that I could provide this guide here. Let’s start with the basics of the programming language, Swift.

Unlike C and some other programming languages, Swift is pretty simple and user-friendly. The syntax is usually understandable and does not involve the use of semicolons at the end of each line of code (Thank God!). So here are some basics of the programming language.

Variables and Constants

There are different initialization for constants and variables in Swift. Once initialized, a constant’s value cannot be updated but a variable can be updated. The following syntax is used to declare a constant.

let x = 100

Now, the type of the constant or variable is automatically detected but can be specified too:

var x:Int = 100

The “var” code is used for declaring variables. Calculations can be performed using simple operators just like any other programming language.

var numberofboxes = 10

var priceofbox = 50

var total = priceofbox*numberofboxes

print(total)

The print function is used to display an output. The variables’ type can be converted in two ways:

var cost = 10

print(“Total price is \(cost)”)

Or:

var cost = 10

print(“Total price is ” +String(cost))

Control Flow

If you are familiar with any programming language, you must know about if-else statements. Swift has two types of control flow statements. The if-else statements and the switch-case statements:

var count = 100

if count>=70{

print(“Price is less”)

}else if count>=50 && count<70{

print(“Price is okay”)

}else{

print(“Not okay at all”)

}

The same code written using switch-case will look like this:

var count =100

switch count{

case 70…:

print(“Price is less”)

case 50…70:

print(“Price is okay”)

default:

print(“Not okay at all”)

}

Note that there are three dots “…” for a range. This is an inbuilt feature in Swift to define a range of data.

Arrays and Definitions

Arrays are a common type of variable in programming languages. In swift, initializing an array is extremely simple. An array is used to store multiple values in a single variable.

var booklist = [“Harry Potter”, “Sherlock Holmes”, “Lord of the Rings”]

You can access a specific item in the array by calling its index or position.

booklist[0]

This code will call the first item in the array. Some predefined functions exist that can be used with arrays, like the append function to add an item to the array.

booklist.append(“Authority”)

booklist.count

This will return the value of “4” since there are four values in the array.

For Loop

A for loop can be used to retrieve all the values of an array but it can also be used for other purposes.

for index in 0…booklist.count-1{

print(booklist[index])

}

Another method is :

for book in booklist{

print(book)

}

Apart from arrays, another type of collection that is similar in function is dictionary. The only difference between the two is that each value in the dictionary has a unique key that can be used to identify the value (unlike the index number in an array).

var booklist = [“98938492”: “Harry Potter”, “3939204”: “Sherlock Holmes”, “3284984”: “Lord of the Rings”]

booklist[“98938492”]

The second line of code can be used to retrieve the first book as its unique key (ISBN number in this case) has been called.

The following code can be used to print all the values in the dictionary:

for (key, book) in booklist{

print(“ISBN: \(key)”)

print(“Book: \(book)”)

}

The important difference to note is that the items of a dictionary aren’t saved in the order of initialization.

Optionals

If you wish to declare a variable that can have no value, you must make it an optional variable. Swift does not accept initialization without assigning a value.

var message

The above code will yield an error because no value is assigned to the variable. In order to make it an optional variable, you must use the following code:

var message: String?

Note that it's compulsory to denote the type of the variable if it's an optional variable. If the optional variable has no value, a value of ‘nil’ is automatically assigned to it.

Swift forces you to check the optional variable. So how do you use the variable? There are two methods to do so:

Forced unwrapping

var message: String?

message = “Hi”

if message!=nil{

print(message!)

}

We check if the variable message is not nil and then we must put an “!” after the variables name while accessing it to tell Swift what we have verified that it contains a value.

Optional Binding

This is the preferred method.

if let message1 = message {

print(message1)

}

This checks if message has a value, then assigns the value to the temporary variable message1, and then we can use the temporary variable and not use the “!”.

Creating UI View

Now let’s try to play around with the UI and create a view element. It is the most basic element in the user interface and we will try to display an emoji and its meaning on a view pane.

The code written above can be used to create an emoji dictionary. The last two lines of the code are for creating the UI View and declaring its size, and background color. The UIView object isthe view pannel.

The following code can be used to add a label to the view panel. A UILabel object is used and its size is declared. Then, we set the text in the label as the emoji, and then we set the font size. Finally, in the last line of code, we add the label to the view panel.

Using similar code, you can create more labels and create the following output:

Don’t get me wrong here, you don’t need to create UI elements using complex codes all the time. XCode allows you to graphically add components and manage your UI elements so you don’t need to worry about that. Now, you are ready to create your first app. By ready, I mean you will learn more along the way but you have the basic knowledge and are ready to create something. Goodluck reading the next chapters!

--

--