Beginning Swift Programming Part 1 — Variables, Constants, and Types

“A tiny sprout growing in fine sand casting long shadow” by Evan Kirby on Unsplash

I know there are a lot of tutorials out there, Apple has good resources for learning Swift, including their WWDC videos (Even the older videos are still relevant so don’t be afraid to look at videos a few years back). Paul Hudson’s series, Hacking with Swift, is great for conceptual learning and his series is how I got started. Ray Wenderlich also has some very in-depth tutorials but most require you to have a working knowledge of the APIs before you get there. I rely on Ray Wenderlich for one-offs. Finally I found Cocoacasts for information on Core Data.

I would like to create a new part in this series every couple of days. Depending on what is covered in the topic may require more time to write.

How This Tutorial is Different

Many tutorials show you how to do something, they hardly ever explain why you do something a certain way. My goal is to teach you the why to the best of my own abilities and adding in feedback from the community.

Many tutorials throw everything at you all at once, I plan to go into detail on the topic(s). You will learn slowly, but by the time you are done with each part, I hope I will have been able to teach you more than what you would have learned reading the same content somewhere else.

What This Tutorial Is

This tutorial is designed in a way that you will learn the basics of programming in Swift. Many things I will teach are transferrable to other languages, but all of the syntax is written in Swift, your mileage using the same syntax may vary.

While this tutorial is not designed to teach you how to make your first app (see below), it will teach you the basic building blocks that you will use over and over again to make your first app.

What This Tutorial Isn’t

This tutorial will not teach you how to use Xcode or how to make your first mobile app. I will not teach how to build user interfaces, use auto-layout, how to use <insert framework here>, or what the various filetypes used in iOS are.

Maybe in the future I’ll write series that dive into these other topics, but for now, my only goal is to teach the language and how things relate to the language.

The Series Objective

The objective of this entire series isn’t to push out another programmer who barely knows anything, it is to teach new programmers what programming really is. To provide the reader with a better understanding, both from a classroom and practical standpoint, of programming in general. To give new programmers a better understanding of the concepts that will help them through interviews and throughout their career.


This tutorial assumes you know:

  • What a computer is
  • What programs are
  • Enough logic to understand what the answer to 2+ 2 is
  • Enough logic to realize if there is milk in your refrigerator

If you have a Mac you can follow along by downloading Xcode from the Mac App Store and create a new Playground to follow along.

If you are on Windows you can follow along at repl.it using Swift. Please note at the time of this writing Repl.it only supports Swift 3.

If you are using linux, you can download Swift for Ubuntu at Swift.org, 14.04 and 16.04 are currently supported. Your mileage may vary and there are various places with tutorials on how to get it running on other Debian-based distributions.


Photo by Igor Ovsyannykov on Unsplash

A Primer

You computer has a special place to hold things that are used by programs, it’s called memory, more technically Random Access Memory, or simply called RAM. Random Access Memory is laid out in blocks, think of lego blocks, each block can hold so much data. Data is stored in bits or bytes.

8 bits = 1 byte

1024 bytes = 1 Kilobyte (KB)

1024 KB = 1 Megabyte (MB)

1024 MB = 1 Gigabyte (GB), and so on, and so on.

I know your eyes may be watering at this point if you’ve never seen this before but it’s something you need to understand if you want to learn how to write programs.

We will get into this a little more later on when we talk about types (among other things), but I wanted to talk about this a little before we continue.

Enough with the upfront stuff. Let’s start!

Photo by Iker Urteaga on Unsplash

Variables

Simply stated, variables store data that can be changed.

Variables in Swift are declared with the keyword var followed by a letter, word, or short phrase that means something to you in relation to the variable. Variables are then instantiated by adding an equal sign (=) followed by the value it should hold.

Behind the scenes your computer does a few things when you create a new variable. First it looks at var a and says “Hey, I’m going to need to ask RAM for a memory, let’s see how much.” Then it looks at = 1 and says “OK, I need to ask RAM for enough space to hold the number 1.” It asks the RAM for the space, if RAM doesn’t see an issue with giving it that space, RAM says “Hey I can take it” and the value is stored in memory.

The same thing happens when name is instantiated with the value Bob and when physicsRoomNumber is given 123 B.

If you ever want to change the value of a variable it’s simple.

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, in other words we are telling the compiler we need to create a variable here. A compiler is the program that converts your program from human readable code to something the computer can understand called machine code. Once the variable is created, we don’t need to keep creating it, so we just address it by it’s name a and give it whatever value it needs to be.

“Scrabble tiles out of focus” by Moritz Schmidt on Unsplash

Constants

Constants store values that cannot change.

OK, so why would I ever want to store a value that cannot change? Most everything in our life changes daily, we get older, we move from one place to another, even programs need to change to perform work, so why would we ever want a value we cannot change?

Constants are used for names, places, things, dates of birth, dates of marriage, dates of death (until the zombie apocalypse comes).

Constants are declared using the let keyword. They are instantiated the same way variables are. The only difference is if you try to change it later, the compiler will yell at you. Well not really yell, but it will throw some red on the screen complaining about how you can’t give it a different value. Lets see how constants are created.

These are all things that come to mind when I think constant values from an outside the programming world perspective. Behind the scenes much of the same stuff happens as when you created the variable.

Later on in this series I’ll talk more about how they are used in programming and how you can use variables and constants together.


“Close-up of the definition of the word “focus” in a French dictionary” by Romain Vignes on Unsplash

Types

On to the final section, what are types?

Types are the different types of values that you can store in variables and constants. I’m only going to cover the basics here, we will get into advanced types later on.

  • String — a string type can contain any number of characters (even emoji 😀). Whether you just use a or supercalifragilisticexpialidocious or even Eight grapes for eight apes it doesn’t make a difference. Just be sure to wrap your variable in “quotes” let myName = "Bob" or var rain = "falls down" Remember how we talked about memory at the beginning? Each character in a string whether it’s a space or an actual letter takes 2 bytes. This is important for you to know later on, but for now, just know that the compiler handles all of this for you.
  • Int — Int is short for Integer, remember in Math class when we used Integers? Int 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. If you are a gamer the 2 billion number might look familiar, this is usually the high score of all the cheaters (or very good players). In Swift, Int works for both of these numbers and fortunately for us, since Apple forced all new apps to use 64-bit so you only have to worry about the big 9 quintillion number. While it’s great to know the full number, you really only need to know when you are getting close to that number. Also don’t try to instantiate a variable with an integer value containing commas, you’ll get yelled at, instead just type the number as 2000 or for easier reading for large numbers use underscores 2_000. This is legal syntax in Swift. 32-bit integers are stored in 32-bits / 8-bits = 4 bytes. 64-bit integers are stored in 64-bits / 8-bits = 8 bytes.
  • Doubles/Floats — So yes these are two different types, but they both work in the same way, we have Int for whole values, but 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 accuracy for calculating moon trajectories, then you might go with a double, if you need to store coordinates on Earth or figure out how much change is due, you go with a float. Say we have var myDouble = 0.1234567 myDouble would be equal to exactly that. If var myFloat = 0.1234567 and we displayed the value we would see 0.123457 what happened to the 6? Well because floats are less precise, we only get 6 decimal places and the value is rounded to the nearest value, in this case 7 rounds to 10, and we carry the 1 over to the 6 giving us the final value. Since floats are 32-bit values, they are stored in 4 bytes. Doubles are 64-bit so they are stored in 8 bytes which is how we get more precision.
  • Bool — Booleans, or Bool for short, are named after George Boole who came up with them. Booleans are really easy to learn. The value can either be true or false. They are instantiated with var madeItSo = true. We will talk about these more in detail later but they are the basis on how you make decisions in programs. Booleans take up 1 byte.
  • Comments — ok you got me, comments are not a type but they help you make notes in your code. You don’t want to write something, come back to it a year later and not know what it’s doing. Comments help you out. There are two types, single line comments // and multi-line comments as shown below. I will use these from here on to describe what is going on in my examples.

Now that I’ve covered some of the types you will encounter, we can talk about the case when you know you will need a variable to store a value but it doesn’t need a value right away. This is where we declare a value and forget about it until we need it again.

Up until now all you’ve seen is where we instantiated a variable or constant and it inferred it’s type by the value we gave it. When you only declare a variable it has no idea what type it can hold, because of this we get yelled at by the compiler because it doesn’t know how much memory it will need. It is an easy fix.

Summary

So today you took your first steps, you learned a little about how programs put variables and constants in memory and what a few of those things are and how much space they use up. 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.

What’s Next?

Next up in the series we will go over value types versus reference types, pointers, and collection types.

I am not affiliated with Apple, Inc, HackingWithSwift.com, RayWenderlich.com, or Cocoacasts.org. Any recommendations are my own. The links are being provided as a convenience and for informational purposes only.