Swift Basics

Yash Awasthi
TechShots
Published in
8 min readMay 12, 2019

What is the purpose of this series?

This series is designed in a way that you will learn the basics of programming in Swift. Many things I will explain here are transferrable to other languages, but all of the syntax is written in Swift. The objective of the series is to provide the reader with a better understanding both from a classroom and practical standpoint and to learn the concepts that will help them through interviews and throughout their career.

Why Swift?

Swift is a relatively new programming language for iOS, macOS, watchOS, and tvOS app development. Swift 4.2 is the current stable version. Apple is also pushing developers community to build apps on Swift. While Objective-C is a stable and mature programming language, Swift is growing faster and the future for iOS development. It is more readable, faster and type-safe. It can also be used in backend development. Learning iOS development with Swift doesn’t prevent a programmer from learning Objective-C at some point in the future. Both have mostly identical underlying framework with different syntax. Later on, I will cover pros-cons of using Swift vs Objective-C. For now, Let’s start with Swift :)

This tutorial assumes that you have knowledge of basic programming stuff.

Variables

Well, Variables, as the name suggest, is something that stores data which could be changed.

Variables in Swift are declared with the keyword var followed by a letter. Variables are then instantiated by adding an equal sign (=) followed by the value it should hold.

var str = "Hello, I am groot"
var age = 22
age = 24

Behind the scenes, your computer does a few things when you create a new variable. First, it looks at var strand says “Hey, I’m going to ask RAM for memory, let’s see how much.” Then it looks at = 22 and says “OK, I need to ask RAM for enough space to hold the number 22.” It asks the RAM for space, then the value is stored in memory.

You see that we used the keyword var the first time but we didn’t include it the second time. The reason for this is that var is only used to declare variables, not when we are changing its value.

Constants

Constants store values that cannot change. For example, your date of birth.

Constants are declared using let keyword. They are instantiated the same way variables are. The only difference is if you can’t change it later, the compiler will throw some red on the screen complaining about how you can’t give it a different value. and if you really need to change it then declare it as a variable.

let dateOfBirth = "20-07-1996"
let avengerName = "Hulk"

Identical things happen behind the scenes when you declare a variable or a constant.

Types.

Types are a different kind of values that you can store in variable or constant.

Swift provides its own versions of all fundamental types:

  • Int for integers. Int(Integer) can be any positive or negative whole number within a range between -2,147,483,648 and 2,147,483,647 in 32-bit programs and -9,223,372,036,854,775,808 and 9,223,372,036,854,775,807 on 64-bit programs. 32-bit integers are stored in 4 bytes(Int32) and 64-bit integers are stored in 8 bytes(Int64).
  • Doubleand Float for floating-point values. Since floats are 32-bit values, they are stored in 4 bytes. doubles and floats work for floating-point numbers or numbers with decimal places. Floats are different from doubles as they are less precise than doubles, this doesn’t mean they shouldn’t be used, it just means if you need more accuracy use Double. Doubles are 64-bit so they are stored in 8 bytes which is how we get more precision.
  • Bool for Boolean values (The value can either be true or falseBooleans take up 1 byte.
  • String for textual data. Each character in a string whether it’s a space or an actual letter takes 2 bytes.

There are also primary collection types, Array, Set, and Dictionary.

  • Array contains ordered like elements which are addressable by their index. The index is defined by the number of items from the beginning of the array. If we defined an array as such
var avengers = ["Ant-Man", "Spider-Man", "Black-Widow", "Iron Man", "Hulk"]

no offense to other superheroes or universe. you can define your array in a similar fashion. Here Avengers[0]will give me the value of “Ant-Man” because index starts from zero.

Arrays are defined and declared with the type surrounded in brackets as in this example var yourIntegerArray = [Int]()

If you access Avengers[4] , it will give you the value of Hulk, but if you access Avengers[5] where 5 is a length of your list. You are going out of bounds of your collection because of the index starts from 0 and ends at 4. So you just need to be careful about staying within the bounds of the array, if you go outside of the array you will run into problems. Most of the time the computer will save you saying “index out of bounds” or something similar to that. If you run into this issue while your program is running, it will crash.

  • Set contains values which are unique. An array can afford to have duplicates but not Set. So if your use case is to store unique values somewhere, voila Swift provides you this Collection Type. For example,
    you have a box with 2 candies, 2 chocolates, 1 banana, and someone asks you to list out different types of items in your box.
var itemsInBox = Set<String>()
itemsInBox.insert("candy")
itemsInBox.insert("chocolate")
itemsInBox.insert("banana")
  • Dictionary contains the unordered collection of key-value pair.

    A dictionary stores associations between keys of the same type and values of the same type in a collection with no defined ordering. Each value is associated with a unique key, which acts as an identifier for that value within the dictionary. Unlike items in an array, items in a dictionary do not have a specified order. You use a dictionary when you need to look up values based on their identifier, in much the same way that a real-world dictionary is used to look up the definition for a particular word. For example.
var myDict = [String : String]() //Declaring Dictionary of which type you wantmyDict["name"] = "Hulk" //Key "name" have value as Hulk
myDict["hobby"] = "Smash"

Very Important Note: Swift is a type-safe language, which means the language helps you to be clear about the types of values your code can work with. If you declare String and try to use it as Int the compiler shows an error.

Suppose in the above example you want to define the age of your superhero( :P)

myDict["age"] = 24 
/*Will show an error because you declared values of dictionaries as String */

A possible workaround here to avoid an error.

myDict["age"] = "24"

But what? why? This is not fair. Age is an integer why are you declaring it as String you may ask. Well, we have a solution around that, which we will discuss in our next article. (Its fun to keep the suspense on).

Moving on, keeping the previous point in mind. Few more important syntax you might wanna know.

Type Annotations

You can provide a type annotation when you declare a constant or variable, to be clear about the kind of values the constant or variable can store.

var myName : String
myName = "Strongest Avenger"

This is something useful where you can initialize kind of values your constants or variables require in your program later on.

Comments

Well, you should aim for writing self-readable code, but hell yeah comments are important.

/* this is the start of the commentThis is a multi-line comment
declaring a string without type annotation*/
var myString = "Not a comment"
//Single Line Comment
let age = 20
let myName = "Thor" //Some people prefer this
let yourName = "Thanos" /* Some people prefer like This */

Cut to the point.

// is used for a single line comment.
and for multiline comments, you enclose your lines between /* and */

Semicolon

If you are familiar with other languages, you know what I am talking about,
even if you are not it is okay to read about it.

Don’t use semicolons. ( Wait… What???) As you can find on Apple resource — it can be used for multiple statements in a single line. But what about clear code?

Try to avoid writing your code like this. It won’t do justice to readability and then you need to use semicolons.

let x = 40.0; let y = 20.0; print("(x, y): (\(x),\(y)")

Why not write to like this.

let x = 40.0
let y = 20.0
print("(x, y): (\(x),\(y)")

It is more readable and without semicolons.

Ohh I almost forgot about writing Print Statements.

Printing Constants and Variables

You can print the current value of a constant or variable with the print(_:separator:terminator:) function:

let age = 27
print("User age is: \(age)")
print("User age is: " + String(age))
print(String(format: "User age is: %d", age))

Well, I prefer the first way but if you know other programming languages, you can find it easy to use second and third way depending upon your choice.

Yeah, I know this is a long article but a couple of things I will talk about it here and then resume from next article.

Type Aliases

A type alias allows you to provide a new name for an existing data type into your program. After a type alias is declared, the aliased name can be used instead of the existing type throughout the program.

Type alias does not create new types. They simply provide a new name to an existing type.

The main purpose of typealias is to make our code more readable, and clearer in context for human understanding.

It is declared using the keyword typealias as:

typealias name = existing type

For example,

typealias StudentName = String
let name:StudentName = "Jack"

This will be useful for complex types we are gonna use later.

In Swift, you can use typealias for most types. They can be either:

  • Built-in types (for.eg: String, Int) (You know about this)
  • User-defined types (for.e.g: class, struct, enum) (Later in this series)
  • Complex types (for e.g: closures) (Later in this series)

Summary

Oh, you have been patient but glad you took your first steps, you learned a little about how programs put variables and constants in memory. A little bit about different types. It’s slow learning, but we are making progress. There are a lot of tutorials out there that are much faster than I will be, but I want to make sure you understand the how and the why.

Thanks for reading this article.

Liked this article?
You can give up to 50 claps: by long pressing the clap button.
if you enjoyed reading this article or learn something new, please tell your friends and share the love for this article.

What's Next?

In the next article, we will go over operators and optionals and then some of the questions which I left unanswered here. Most of the preliminary background information is over, and soon we will be having fun with programming.

For getting updates for interesting articles related to tech and programming to join TechShots.Its a start to a long journey. We will love the developers to be a part of this and publish blogs related to any tech they like. You can also send us suggestions at techshotscommunity@gmail.com.Your feedback is very valuable.

References :

  1. https://docs.swift.org/swift-book/LanguageGuide/StringsAndCharacters.html
  2. https://docs.swift.org/swift-book/LanguageGuide/CollectionTypes.html

--

--